我有一个表格,其中包含以下形式的每月数据:
Date | Value
2018-06 | 100
2018-07 | 105
2017-06 | 90
2017-07 | 92
获取此数据并计算每个月的同比回报的最佳方法是什么? 我希望它看起来像:
Date | YoY growth
2018-06 | 0.11111
2018-07 | 0.1413
答案 0 :(得分:0)
使用DISTINCT ON month仅选择月份。然后使用反向列表中的LEAD窗口函数(通过ORDER BY d DESC)获得当前年份之前的年份
实时测试:http://sqlfiddle.com/#!17/5be39/2
select
distinct on ( date_part('month', (d || '-01')::date) ) -- get the months only
-- ORDER BY d DESC sort the list from most recent to oldest.
-- so LEAD here actually refers to previous year
d,
v,
lead(v) over(partition by date_part('month', (d || '-01')::date) order by d desc),
( v / lead(v) over(partition by date_part('month', (d || '-01')::date) order by d desc) )
- 1 as YoyGrowth
from progress
输出:
| d | v | lead | yoygrowth |
|---------|-----|------|--------------------|
| 2018-06 | 100 | 90 | 0.1111111111111111 |
| 2018-07 | 105 | 92 | 0.141304347826087 |
答案 1 :(得分:0)
我只是解析日期并使用lag()
:
select date, value, prev_value,
(value - prev_value) / prev_value as YOY_growth
from (select t.*,
lag(value) over (partition by right(date, 2)
order by left(date, 4)
) as prev_value
from t
) t
where prev_value is null