How to count the number of occurrences per month? - sql

I have a program and want to generate reports from it. The program is for a grocery store that does deliveries. A customer places an order and the program captures the various items that the customer wishes to purchase, e.g. Order 21 and the program lists the various items relating to that specific order.
I would like to generate a SQL query that counts the number of orders that customers place each month and want it to look like this
No of orders Month
10 Jan
20 Feb
30 March
The SQL that I had which is
SELECT COUNT(OrderID) AS "Number Of Orders", datepart(month, order_date) AS "Month"
FROM "ORDER"
Group by datepart(month, order_date);
Displays
Number of Orders Month
16 9
However this is the count of all the orders for the various months and is only displayed in month 9 (September.)

Hope this will help:
select COUNT(OrderID) as "Number Of Orders",DATENAME(mm,order_date) as "Month" from "ORDER" group by DATENAME(mm,DueDate) order by 2

Related

SQL code to find the total sum of sales amount by each person by day

enter image description here
Hi, I have a data table shown in the image above. I want a result whereby the code finds each person's total (sum) sales amount by day.
e.g., for Salesperson Frank, it returns his sales for Monday, Tuesday, Wednesday, etc.
Thanks
SELECT SalesPerson, Week, Day, SUM(SalesAmount)
FROM myTABLE
GROUP BY SalesPerson, Week, Day
ORDER BY SalesPerson, Week
Use a day number field if you want to order by week day.
If you don't want to group by week, suppress Week field from previous query.

getting sum for each month for several months in a year in sql

I have the following table
image of database in use
i want to get the following kind of results
jan 12500
feb 16500
mar 4500
apr 6500
the query should return a total for each month for desired months.
i know how to do this..
$sql = "SELECT SUM(cost) as january FROM earnings WHERE month= 1 and year= '$2022" ;
to get the sum for a given month but I cant find anything on how to get multiple months at once.
am still new to this
SELECT
SUM(cost) as cost,
month
FROM earnings
WHERE year = :year
GROUP BY month
Sum all entries of cost, per month (GROUP BY) found in year (:year)
Each ROW will have a column cost and month.
If you want to "further" filter the months you can apply another AND clause
AND (month >= 1 OR month <= 6) for January to June
Useful Source:
https://www.mysqltutorial.org/mysql-group-by.aspx

SQL query data that appears for consecutive years

I have tried several times to figure this out but no luck.
I have one table that I am trying to query.
InvNo (primary key),
CustID,
InvAmt,
DatePD
I want to pull all of the customers that have paid at least one invoice for 3 consecutive fiscal years. Fiscal year for this example is Aug 1 to Jul 31 of the following year. Thie InvNo is unique but the custID can appear multiple times depending on how many invoices they have paid. Can anyone help me with this?
For output I need one record per custID and how many consecutive years that CustID has paid an invoice.
CustID 333 ConsecutiveYears 7
You can get the year by either subtracting 8 months or adding four months and extracting the year. Then, lag() can solve the problem:
select distinct custid
from (select t.*, lag(yyyy, 2) over (partition by custid order by yyyy) as prev_yyyy_2
from (select distinct custid, year(dateadd(month, -8, datepd)) as yyyy
from t
) t
) t
where prev_yyyy_2 = yyyy - 2;
The innermost subquery just gets pairs of customers and year. The lag() looks two rows behind. Three years are present if "2 rows behind" is exactly 2 years ago.

SQL Query to recursively track month of purchase

I have a table with customer id and month of purchase. For each customer, I first need to segment them on their first month of purchase, i.e., if a customer did their first purchase on 10 June 2017, then they belong to bucket June 2017. See below sample data table.
Then for each subsequent purchase of that customer (say from June 2017 segment), we need to track the month. For instance, if the June 2017 customer did their second purchase on 25 June 2017 and 3rd purchase on 11 Aug 2017. Then second purchase will be counted in 1st Month (within 30 days of 1st transaction) and 3rd purchase will be counted in 3rd month, as difference between 11 Aug 2017 and 10 June 2017 is 62 days, which lies between 61 and 90 days, hence in the 3rd month.
See below sample output table, although I need it in percentage form (% of customer who did in first month, second month, etc.). In the table, we are showing all the customers who did their first transaction say in Jan 2017 and then how many of them did transactions in subsequent months.
This tracking needs to be done for each customer. While I believe I am comfortable with the first part, wherein I need to segment each customer, I can do that based on first or partition.
I am not sure about how to do this recursively for subsequent transactions.
Thanks in advance for help!
You simply use window functions to define the original month and then conditional aggregation.
You don't mention the database, but this is the idea:
select to_char(first_purchase_date, 'YYYY-MM') as yyyymm,
sum(case when months_between(first_purchase_date, purchase_date) = 1 then 1 else 0 end) as purchases_1,
sum(case when months_between(first_purchase_date, purchase_date) = 1 then 1 else 0 end) as purchases_2,
. . .
from (select t.*,
min(purchase_date) over (partition by customer_id) as first_purchase_date
from t
) t
group by first_purchase_date;
I invented the months_between() and to_char() functions, but you should get the idea.
The above tracks purchases. To get customers, you can use:
(count(distinct case when months_between(first_purchase_date, purchase_date) = 1 then customer_id) /
count(distinct customer_id)
) as month_1_ratio
You can use the lag function to create a column “previous purchase.
Lag(purchasemonth,1) over(partition. by customerid order by purchasemonth) as [PreviousPurchaseDate]
Then simply do a datediff and bucket as you wish.

Determine monthly values of timestamped records

I have a SQL table with the following schema:
fruit_id INT
price FLOAT
date DATETIME
This table contains many records where the price of a given fruit is recorded at a given time. There may be multiple records in a single day, there may be
I would like to be able to fetch a list of prices for a single fruit over the last 12 months inclusive of the current month. So given a fruit_id of 2 and datetime of now(), what would the price values be for December, January, February, ... October, November?
Given the above requirements, what strategy would you use to get this data? Pure sql, fetch all prices and process in code?
Thanks for you time.
Are you talking about min price, max price, average price, or something else?
Here's a quick query to get you started, which includes min, max, and average price for each month for fruit_id 2:
select left(date,7) as the_month, min(price),max(price),avg(price)
from fruit_price
where fruit_id = 2
and date >= concat(left(date_sub(curdate(), interval 11 month),7),'-01')
group by the_month;
If I understand it correctly from -
I would like to be able to fetch a list of prices for a single fruit over the last 12 months inclusive of the current month. So given a fruit_id of 2 and datetime of now(), what would the price values be for December, January, February, ... October, November?
You want the total price for every month for a single year based on the date and fruit_if you pass in.
So,this won't give all months of an year but all months which had a price for year..in case you want all months..you would need to create a dimdate table which will have all the dates...and then join with it..
declare #passeddate=Now() --date to be calculated
declare #fruit_id=2 --fruit id to be calculated
Select
fruit_id as FruitId,
Sum(price) as MonthPrice,
Month(date) as FruitMonth
from SQL_Table
group by FruitMonth,FruitId
where fruit_id=#fruit_id and
Year(date)=Year(#passeddate)
select month(date) as "Month", distinct(price) as "Unique Price" where fruit_id = 2 group by month(date);
I'd try to state as much as possible in SQL that does not require unindexed access to data because it's usually fast(er) than processing it with the application.