sqlsql-serversql-date-functions

sql group by end of the week on Sundays


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:

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 ...


Solution

  • if it can help, in Python, (and in general the algorithm) would be:

    df['week'] = (
    np.ceil(
    (
    df['DATE'].dt.day
    - 7 +
    df['DATE'].dt.to_period('M').dt.start_time.dt.dayofweek
    )
    /7)
    ).astype(int) + 1
    

    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)