[英]sql: cummulative sum (partition by clients order by date)
请您帮我计算 sql 服务器 2017 中的累积总和。条件是:1)按客户端分区 2)按 date_tm 排序。 理想的结果如下表所示。
create table #clients (client nvarchar(1)
, date_tm datetime
,sum_pay int
, desirable_result int)
insert into #clients
(client, date_tm, sum_pay, desirable_result)
select '1', '2020-01-01', 10, 10 union all
select '1', '2020-01-02', 20, 30 union all
select '2', '2020-01-03', 20, 60 union all
select '2', '2020-01-01', 20, 20 union all
select '2', '2020-01-02', 20, 40 union all
select '3', '2020-01-01', 20, 20 union all
select '3', '2020-01-04', 20, 70 union all
select '3', '2020-01-02', 30, 50
select * from #clients
drop table if exists #clients
非常感谢。
在下面找到
select c.*,sum(sum_pay) over(partition by client order by date_tm)
from #clients c
您可以使用 sum()over() window function 如下:
select * ,SUM (sum_pay) OVER (partition by client order by date_tm) AS cummulativesum from #clients
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.