我有一个数据集,按成员,按月,按产品记录收入。我可以按成员总结收入:
select sum(revenue), member, month from member_revenue group by member, month
我想计算按月更改的月份是按成员收入,理想情况下无需再次调用表格中的数据。
答案 0 :(得分:1)
您可以使用已有的查询作为内部查询,并使用外部查询将其包装,该查询使用lag
窗口函数减去每个月的上个月收入:
SELECT member,
month,
month_revenue,
month_revenue -
LAG(month_revenue) OVER (PARTITION BY member
ORDER BY month ASC) AS revenue_change
FROM (SELECT member, month, SUM(revenue) AS month_revenue
FROM member_revenue
GROUP BY member, month) t
答案 1 :(得分:0)
只需使用lag()
:
select member, month, sum(revenue) as this_month_revenue,
lag(sum(revenue)) over (partition by member order by month) as last_month_revenue
from member_revenue
group by member, month;
注意:这假定所有月份都有收入。 LAG()
获得前一行的收入,即使它不是前一个月。