| date_key | cust_id | sales |
|---|---|---|
| 2022-01-01 | 1 | 30 |
| 2022-01-02 | 1 | 35 |
| 2022-01-05 | 1 | 38 |
| 2022-01-10 | 1 | 20 |
| 2022-01-11 | 1 | 35 |
| 2022-01-01 | 2 | 20 |
| 2022-01-02 | 2 | 25 |
| 2022-01-04 | 2 | 38 |
| 2022-01-09 | 2 | 20 |
| 2022-01-15 | 1 | 35 |
| 2022-01-11 | 3 | 35 |
I would like to get all customer_ids in the current period and left join the difference in sum(sales) between period 2022-01-01 -2022-01-05 and sum(sales) from period 2022-01-06 - 2022-01-11 .
How would you achieve this in windows function? Currently I am using ctes
with
users as(
select
distinct cust_id
from
tableSales
where date_key between date('2022-01-06) and date('2022-01-11)),
currentPeriod as(
select
distinct cust_id
,sum(sales) sales
from users
left join tableSales using (cust_id)
where date_key between date('2022-01-06) and date('2022-01-11)
),
previousPeriod as(
select
distinct cust_id
,sum(sales) sales
from users
left join tableSales using (cust_id)
where date_key between date('2022-01-01) and date('2022-01-05)
)
#-----------------------
Select
distinct cust_id
,cp.sales - pp.sales deltaSales
from users
left join currentperiod cp using(cust_id)
left join previousperiod pp using(cust_id)
There must be a shorter way to achieve this using windows function? Please do help.