【问题标题】:quarterly difference in sum(Revenue) saved in a new column MySQL保存在新列 MySQL 中的总和(收入)的季度差异
【发布时间】:2021-04-29 11:12:03
【问题描述】:

我需要在我的表中添加一个新列,该列将具有新季度收入总和与上一季度之间的差异。 我的数据如下所示:

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` 

【问题讨论】:

  • 最初的+5从何而来?
  • 您在 * 之后缺少逗号

标签: mysql sql date time difference


【解决方案1】:

据我所知,您想要的是与上一个季度的差异,而不是。那将是:

select t.*,
       (t.Revenue - lag(t.Revenue) over (partition by website order by Year, quarter)) as difference 
from table t;

注意网站使用partition by

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 2020-09-12
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    • 2021-01-07
    相关资源
    最近更新 更多