sql:累计和(按客户划分,按日期排序)

sql:累计和(按客户划分,按日期排序),sql,Sql,请您帮助我计算sql server 2017中的累计金额。条件是:1)按客户划分2)按日期排序。理想结果如下表所示 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', 1

请您帮助我计算sql server 2017中的累计金额。条件是:1)按客户划分2)按日期排序。理想结果如下表所示

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()窗口函数,如下所示:

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