[英]Can we group sum in previous period in SQL
我需要在SQL中将上一时期的总和分组。 这是我从简化客户(客户A,B和C)获得的数据
Customer Year Month Order
A 2019 5 10
A 2019 4 5
A 2019 3 3
A 2019 2 1
A 2018 12 3
B 2019 5 1
B 2019 4 2
B 2019 3 1
C 2019 5 2
C 2019 4 1
C 2019 2 1
C 2019 1 3
预期输出为总和上一期间的订单
例如,第一行的“预期输出”为12,因为它在客户A中的上一个期间(7 + 4 + 3 + 0)之和。
另一个示例,第二行的预期输出是7,因为它在客户A中上一个期间(4 + 3 + 0)的总和。因此,下表是上表的预期输出
Customer Year Month Order Output
A 2019 5 10 12
A 2019 4 5 7
A 2019 3 3 4
A 2019 2 1 3
A 2018 12 3 0
B 2019 5 1 3
B 2019 4 2 1
B 2019 3 1 0
C 2019 5 2 5
C 2019 4 1 4
C 2019 2 1 3
C 2019 1 3 0
我需要在SQL中执行此操作
首先,我将更改列的名称(年,月和顺序为mysql保留字或函数)。 您可以使用以下子查询来做到这一点:
select customer,
`year`,
`month`,
`order`,
(select sum(output)
from yourtable b
where a.customer=b.customer and (a.year>b.year or (a.year=b.year and a.month>b.month)))
from yourtable a
您要做的是每一行,最后一列是具有相同客户并且年份比客户中的年份低的所有其他列的输出总和,或者如果年份相同,则月份更低
在MySQL 8+中,应使用窗口函数:
select t.*,
sum(output) over (partition by customer order by year, month)
from t;
唯一需要注意的是,这样做更为简洁,但是它也应该具有更好的性能。
这可以通过窗口功能来实现。 以下链接提供了示例
LAG([,offset [,default_value]])OVER(分区按expr,... ORDER BY expr [ASC | DESC],...)
http://www.mysqltutorial.org/mysql-window-functions/mysql-lag-function/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.