简体   繁体   中英

SQL - lag variable creation using window function

I have daily city level data with some counts. I have to aggregate this data at monthly level(1st day of each month) and then create lag variables based on last 1 week from 1st day of month.

输入数据

I have used following code to create lag variables for last 1 month using (after aggregating data at monthly level ( with 1st date of month)

sum(count) over (partition by City order by month_date rows between 1 preceding  and 1 preceding) as last_1_month_count

Is there a way to aggregate data at monthly level and create lag variables based on last 7,14,21,28 days using window function?

you can use this L

select 
    CITY
    , month(Date)
    , year(date)
    , sum(count)

from table1
where date < Datediff(days , 7 , getdate())
group by 
    City
    , month(Date)
    , year(date)

I think you're looking for something like this. The first cte summarizes city counts to the day, week, month, year. The second summarizes the counts to the week, month, year. To group sales by weeks starting from the 1st day it uses the DAY function along with YEAR and MONTH. Since DAY returns and integer, groups of distinct weeks can be created by dividing by 7, ie DAY(day_dt)/7.

One way to get the prior week sales would be to join the week sales summary cte to itself where the week is offset by -1. Since the prior week might possible have 0 sales it seems safer to LEFT JOIN than to use LAG imo

with 
day_sales_cte(city, day_dt, yr, mo, wk, sum_count) as (
    select city, day_dt, year(day_dt), month(day_cte), day(day_dt)/7, sum([count]) sum_counts
    from city_level_data
    group by city, day_dt, year(day_dt), month(day_cte), day(day_dt)/7)
wk_sales_cte(city, yr, mo, wk, sum_count) as (
    select city, yr, mo, wk, sum(sum_counts) sum_counts
    from sales_cte
    group by city, yr, mo, wk)
select ws.*, ws2.sum_sales prior_wk_sales
from wk_sales_cte ws
     left join wk_sales_cte ws2 on ws.city=ws2.city
                                   and ws.yr=ws2.yr
                                   and ws.mo=ws2.mo
                                   and ws.wk=ws.wk-1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM