简体   繁体   中英

sql: cummulative sum (partition by clients order by date)

Would you, pleace, help me, to count cummulative sum in sql server 2017. Condition is: 1) partition by client 2) order by date_tm. Desirable result is in the table below.

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

Thank you very much.

are finding below

 select c.*,sum(sum_pay) over(partition by client order by date_tm)
 from #clients c

You can use sum()over() window function as below:

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

with this code you can compare, desirable_result and cummilative sum

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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