I am working on a database which includes sales information; the table for this is fairly basic:
ContractID(PK), CustomerID(FK), SalesAgent(FK), Value(int), SalesDate(Date)
And I have a requirement to produce a monthly sales report - sounds simple; group the dates by month.
However, the client has a non-calendar monthly sales structure - effectively, most months are 28 days, December is 42 days, and April & August are 35 days - this means that all months start on a Monday, and the extra weeks are allocated to Easter, High Summer, and Christmas, when business is usually slower.
So effectively I have a calendar like this:
Month. StartDate, EndDate
1. 20210104, 20210131
2. 20210201, 20210228
3. 20210301, 20210328
4. 20210329, 20210502
5. 20210503, 20210530
6. 20210531, 20210627
7. 20210628, 20210725
8. 20210726, 20210829
9. 20210830, 20210926
10. 20210927, 20211024
11. 20211025, 20211121
12. 20211122, 20220102
13. 20220103, 20220130
14. 20220131, 20220227
etc.
What's the best way to allocate each sale to a period above to group for reporting - I was initially thinking of having the above table as a CTE within my query, then SELECT based on the SalesDate being before and after the start and End Dates in the above, but what join do I then use to link that to the main query?
Is there no way around this other than to run the query for each specific period as listed above, or can this be done with a UNION?
(hope this makes sense)
Join your sales data and calendar, template
with calendar(Month, StartDate, EndDate) as(
..
)
select ..
from calendar
join sales on sales.date between calendar.StartDate and calendar.EndDate
group by .. calendar.Month ..
Related
I'm trying to find the average of net total for a given month, based on previous years to help show things like seasonal trends in sales.
I have a table called "Invoice" which looks similar to the below (slimmed down for the purpose of this post):
ID - int
IssueDate - DATE
NetTotal - Decimal
Status - Enum
The data I'm trying to get, for example would be similar to this:
(sum of invoices in June 2018 + sum of invoices in June 2019 + sum of invoices in June 2020) divided by number of years covered (3) = Overall average for June
But, doing this for the full 12 months of the year based on all the data (not just 2018 through to 2020).
I'm a bit stumped on how to pull this data. I've tried subqueries and even tried using a SUM within an AVG select, but the query either fails or returns incorrect data.
An example of what I've tried:
SELECT MONTHNAME(`Invoice`.`IssueDate`) AS `CalendarMonth`, AVG(`subtotal`)
FROM (SELECT SUM(`Invoice`.`NetTotal`) AS `subtotal`
FROM `Invoice`
GROUP BY EXTRACT(YEAR_MONTH FROM `Invoice`.`IssueDate`)) AS `sub`, `Invoice`
GROUP BY MONTH(`Invoice`.`IssueDate`)
which returns:
I see two parts to this query, but unsure how to structure it:
A sum and count of all data based on the month
An average based on the number of years
I'm not sure where to go from here and would appreciate any pointers.
Ideally, I'd want to get the totals from rows where "Status" = "Paid", but trying to crack the first part first. Walk before running as they say!
Any guidance greatly appreciated!
Basically you want two levels of aggregation:
SELECT mm, AVG(month_total)
FROM (SELECT YEAR(i.IssueDate) as yyyy, MONTH(i.issueDate) as mm,
SUM(i.`NetTotal`) as month_total
FROM Invoice i
GROUP BY yyyy, mm
) ym
GROUP BY mm;
Just for the Average Amount Part You Could use a query like
Select Date From Your_Table Where Date Like '20__-06-%'
You can arrange it into asc desc order.
I'm in need of some help structuring in-time queries. There's a few of them I need - but I think that if I can be shown how to do one, I can figure out the others.
What I'm after:
-Rolling 12 month view of 'inactive accounts'...ie number of accounts that have not placed an order in the 12 months prior.
-This ideally will be a subquery (in a much larger script) joining back on to a dates table (see below)
January 2015 | # of customers with no orders from 1/2014-1/2015
February 2015 | # of customers with no orders from 2/2014-2/2015
March 2015 | # of customers with no orders from 3/2014-3/2015
etc...
What I'm having trouble wrapping my mind around is how I'd structure a where clause to ensure that it scans all orders and only returns the total of account ID's that had not placed an order in the year prior to that month. I've used different combinations of DATEDIFF, DATESUB etc.
SELECT DATE_FORMAT(order_datetime, '%Y-%m'), COUNT DISTINCT (account_id)
FROM warehouse.orders
JOIN warehouse.accounts ON xyz
WHERE...
It feels like I'm on the right path - I just keep mentally going in circles trying to figure this out.
Cheers and thanks in advance.
I don't have enough reputation points to simply comment on your question. I don't fully understand it though.
Are you using SQLServer/TSQL or MySQL?
Do you want to have just one column which calculates the last 12 months' rolling average or 12 columns for the rolling average each month? If it is just one figures for the last 12 months tolling do you want that to be from the current day or the beginning of that month?
If it was SQL Server and a rolling 12 months to now, the calculation could be:
SELECT SUM(CASE WHEN DATEDIFF(y,GETDATE(),order_date_time) < 1 THEN COUNT(DISTINCT account_id) END) as January2015
If you're using MySQL replace GETDATE() with NOW()
If you want one value rolling but to the beginning of the month then you could use:
SELECT SUM(CASE WHEN DATEDIFF(y,DATEADD(M, DATEDIFF(M, 0, GETDATE()), 0),order_date_time) < 1 THEN COUNT(DISTINCT account_id) END) as January2015
If I've missed the point entirely, please let me know and I'll happily amend the answer
You should query between dates, in order to get the count of events for each id.
select case
when count(account_id)<0 then 'INACTIVE'
when count(account_id)>0 then 'ACTIVE'
from warehouse.orders
where data_format(order_datetime, '%m/%Y') between '1/2014' and '1/2015'
group by account_id)
Using MySQL and PHP I am building a JSON array to populate a data table.
For the purposed of my question suppose the data table has the following columns:
Year: 2010,2011,2012,2013...<br/>
Month: 1,2,3,4,5...<br/>
Value: 100, 150, 200 etc...<br/>
The table structure cannot be altered and my solution needs come into the MySQL query
The data can be viewed either monthly, quarterly or yearly. Monthly and yearly is achieved easily through grouping by year and month.
Quarterly data can be grouped by calendar quarter (Jan-Mar, Apr-Jun, Jul-Sep, Oct-Dec) by this group statement:
GROUP BY year, round((month/3)+0.3,0)
So where Jan, Feb and March might all have 100 for their value the summed result is 300, same for other months.
Now my problem comes when I want to group values by a financial quarter, for example a quarter that starts in Feb, or any other quarters.
I have a statement that works for the quarter grouping using two variables that can be accessed via the SQL query, start_year (i.e. 2014) and start_month (i.e. 2)
GROUP BY year, (((round(((((month-(start_month-1))+((year-start_year)*12))-((year-start_year)*12))/3)+0.33,0)/4)+4)-floor(((round(((((month-(start_month, '%m')-1))+((year-start_year)*12))-((year-start_year*12))/3)+0.33,0)/4)+4)))*12
which basically will assign a 0,3,6,9 value to each calendar month for the purposes of grouping.
In the financial year starting February this works fine for quarters 1-3, however breaks for the final quarter as it includes Nov and Dec 2014 data and Jan from 2015.
As a result I get 5 rows of data instead of 4.
This is because of the preceding GROUP by year clause, an important addition as we might want to generate a table that views sequential quarters for multiple years.
So what I am looking for is a way of grouping the years together by offsetting the start month.
So when the year starts in Jan it will group Jan-Dec but if we change that to starting Feb it will group Feb-Jan.
Any ideas, suggestions most welcome!
Regards,
Carl
I solved a similar problem just now (a Moodle report aggregating assignment scores by year and quarter) with something like this:
select year(from_unixtime(s.timemarked)) as year, quarter(from_unixtime(s.timemarked)) % 4 + 1 as quarter, count(distinct data1) as "tickets graded" from mdlassignment_submissions s where grade >= 0 group by year, quarter order by year, quarter;
The relevant part for what you're doing is quarter(from_unixtime(s.timemarked)) % 4 + 1 as quarter
As another commenter pointed out, MySQL has a quarter() function, but it doesn't do financial quarters. However, since (as I understand it, at least, based on consulting the relevant wikipedia page) financial quarters are just offset by 1, the % 4 + 1 at the end should convert it.
I'm having issues getting the desired results from my database. The join_service_date and dropped_service_date columns have dates. The rejects have an r in the column if it is rejected.
I want to be able to count the agents sales, rejects, dropped sales and how many of those sales have dropped our service within 0-30 days, 31-60 days or 61-90 days. I got the results I needed from doing several small queries, but I would like to learn or know how to gather the information in a just 1 or as little as possible queries.
Also how would I specify this for a specific month like march or april.
select agentid,
count(join_service_date),
count(dropped_service_date),
count(rejects),
datediff(day, join_service_date, dropped_service_date)
from dbtable
group by agentid
I have a staff timesheet table where i have timestamp of when those records are created. I now want to generate the report so that my start date is Tuesday and end date is next Monday, which is 1 week. Now i need to generate all the records grouped by this weeks time but will be next set of tuesday to monday.
This is like normal GROUP BY WEEK(Timestamp) but the WEEK numbers are not the default ones i need to generate the reports in this custom duration. I have a query working for this which groups the record efficiently by Week 1, week 2, week 3 etc.. which is picked from default mysql calendar i guess. How can i change that to generate reports grouped by custom weeks ?
Can you tel me how the following works as how the dates are picked up ?
SELECT WEEK(pw.date) AS Date,DATE_FORMAT(pw.date,'%d-%m-%Y') AS post_date,
SUM(wages) AS amount,SUM(pw.hours) AS hours,SUM(pw.minutes) AS minutes
FROM pos_sessions pw
GROUP BY YEAR(pw.date), WEEK(pw.date) ORDER BY pw.date DESC
I think this Other Solution is what you are looking for...