繁体   English   中英

sql:累计(按日期按客户排序)

[英]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
SELECT * , 
CASE WHEN desirable_result = cum_sum THEN 'OK' ELSE 'NO' END AS Status
FROM
(
select 
*,
SUM (sum_pay) OVER (partition by client order by date_tm) AS cum_sum
from #clients  as tbl
) as a

使用此代码,您可以比较desired_result 和cummilative sum

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM