I'm calculating some metrics and try to achieve this with a window function. First I calculated WEEKLY_PROFIT delta for current week/CURRENT year vs last week/CURRENT year.
How can I apply a window function to calculate WEEKLY_PROFIT for current week/CURRENT year vs same week number/LAST year?
SELECT TR_YR, TR_WEEK, WEEKLY_PROFIT,
COALESCE((WEEKLY_PROFIT/NULLIF(lag(WEEKLY_PROFIT, 1, 0)
OVER (PARTITION BY TR_YR ORDER BY TR_WEEK), 0))-1, 0) AS DELTA_PROFIT_WEEKLY_VS_CY
FROM base_metrics
GROUP BY TR_YR, TR_WEEK
The table after calculating DELTA_PROFIT_WEEKLY_VS_CY
|TR_YR |TR_WEEK|WEEKLY_PROFIT|DELTA_PROFIT_WEEKLY_VS_CY|
| 2019 | 1 | 500.0 | 0.0 |
| 2020 | 1 | 1000.0 | 0.0 |
| 2020 | 2 | 1500.0 | 0.5 |
| 2020 | 3 | 700.0 | -0.53 |
Here is what I expect after calculating DELTA_PROFIT_WEEKLY_VS_LY (WEEKLY_PROFIT for current week/CURRENT year vs same week number/LAST year)
|TR_YR |TR_WEEK|WEEKLY_PROFIT|DELTA_PROFIT_WEEKLY_VS_CY|DELTA_PROFIT_WEEKLY_VS_LY|
| 2019 | 1 | 400.0 | 0.0 | 0.0 |
| 2020 | 1 | 1000.0 | 0.0 | 1.5 |
| 2020 | 2 | 1500.0 | 0.5 | 0.0 |
| 2020 | 3 | 700.0 | -0.53 | 0.0 |
Your code looks pretty good, except for the GROUP BY
and PARTITION BY
clause:
SELECT TR_YR, TR_WEEK, WEEKLY_PROFIT,
COALESCE((WEEKLY_PROFIT/NULLIF(lag(WEEKLY_PROFIT, 1, 0)
OVER (PARTITION BY TR_WEEK ORDER BY TR_YR), 0))-1, 0
) AS DELTA_PROFIT_WEEKLY_VS_CY
FROM base_metrics;
I feel this is easier done with a left join
. You can handle nulls
with coalesce
if you later wish to
select a.tr_yr,
a.tr_week,
a.weekly_profit,
a.weekly_profit/c.weekly_profit as profit_wow,
a.weekly_profit/b.weekly_profit as profit_yoy
from t a
left join t b on a.tr_yr=b.tr_yr+1 and a.tr_week=b.tr_week
left join t c on a.tr_yr=c.tr_yr and a.tr_week=c.tr_week+1
order by a.tr_yr, a.tr_week;
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.