I have 3 columns in my table:
bill_date (daily data), country, revenues
How to group by country and get sum of revenues if I want to group my bill_date by the end of every week that fall on Sundays ?
To be clearer for the current month ,November 2023 I would like to get following:
- from day 1th November to sunday 5th November : week 1 ( 1 day of month, no matter which day it is , until 1th sunday of the month )
- from 6 November to sunday 12th November : week 2 (week from monday to sunday)
- from 13th November to sunday 19th November : week 3 (week from monday to sunday)
- from 20th November to sunday 26th : week 4 (week from monday to sunday)
- from 27th to thursday 30th : week 5 ( for the last week of every month, I would like to select all the days always starting from monday until the last day of the month, no matter which day will be the end of the month)
I have tried with week datepart
function using SQL Server Management Studio 2018 version but with no success... I cannot see dateweek function in SQL Server Management Studio 2018 ...
4条答案
按热度按时间yyhrrdl81#
if it can help, in Python, (and in general the algorithm) would be:
you're using the first day of each month to establish when the first week of the month ends. example: first day is Monday. you'll have week calculated as ceil((1 - 7 + 0)/7) + 1 = 0 + 1 = 1 Tuesday: ceil((2 - 7 + 0)/7) + 1 = 0 + 1 = 1 ... the first next Monday: ceil((8 - 7 + 0)/7) + 1 = 1 + 1 = 2 and so on
if the first day of the week was Sunday, you'd get ceil((1-7+6)/7) + 1 = 0 + 1 = 1 but on the second day ceil((2-7+6)/7) + 1 = 1 + 1 = 2
the offset must equal the .dt.dayofweek of the first day of the month (because Monday = 0)
g52tjvyc2#
You will need to group your data both by month and week to get the right output.
To group by week specify the first day of week as Monday with
SET DATEFIRST 1
and group the data withDATEPART(wk, bill_date)
.To group by month use
CONVERT(nvarchar(7), bill_date, 121)
to get the first 7 characters of a the date ISO-formatted.wgmfuz8q3#
You can calculate the period-ending date by separately calculating the last-day-of-the-week and last-day-of-the-month and taking the lesser of the two. This can be wrapped up in a
CROSS APPLY
and the result used in theGROUP BY
,SELECT
, andORDER BY
clauses.If using SQL Server 2022 or later, the
DATETRUNC()
andLEAST()
functions simplify the calculations.The
DATEBUCKET()
function can also be used if you wish to avoidSET DATEFIRST
.5rgfhyps4#
First group by country, year, month and week (monday to sunday), then renumber the week (
row_number()
):db<>fiddle