Mysql 新列中保存的金额(收入)的季度差异
我需要在表中添加一个新列,该列将显示新季度收入总额与上一季度收入总额之间的差额。 我的数据如下所示:Mysql 新列中保存的金额(收入)的季度差异,mysql,sql,date,time,difference,Mysql,Sql,Date,Time,Difference,我需要在表中添加一个新列,该列将显示新季度收入总额与上一季度收入总额之间的差额。 我的数据如下所示: Website Year Quarter Revenue cosmo.com 2019 4 10 cosmo.com 2020 1 15 cosmo.com 2020 2 5
Website Year Quarter Revenue
cosmo.com 2019 4 10
cosmo.com 2020 1 15
cosmo.com 2020 2 5
fashion.com 2019 4 10
fashion.com 2020 1 5
fashion.com 2020 2 20
所需输出为:
Website Year Quarter Revenue Difference
cosmo.com 2019 4 10 +5
cosmo.com 2020 1 15 +5
cosmo.com 2020 2 5 -10
fashion.com 2019 4 10 +10
fashion.com 2020 1 5 -5
fashion.com 2020 2 20 +15
首先,我试图查看每年的差异,但出现了语法错误
select *,
`Revenue` - lag(`Revenue`) over(order by `Year`) as difference
from table`
据我所知,你想要的是上一季度的差异,而不是今年的差异。这将是:
select t.*,
(t.Revenue - lag(t.Revenue) over (partition by website order by Year, quarter)) as difference
from table t;
请注意,在网站中使用了
partitionby
。首字母+5来自何处?后面缺少一个逗号*