【发布时间】:2016-09-05 15:28:07
【问题描述】:
我正在尝试对一些数据进行汇总,并且已经看到了简单的方法。但是,我已经对一些数据进行了分组,这会影响我的代码。我目前有日期和付款类型,以及与之相关的总数。
我现在拥有的是:
create table #testdata
(
mdate date,
pmttype varchar(64),
totalpmtamt int
)
insert into #testdata
select getdate()-7, 'DD', 10
union
select getdate() -7, 'SO', 12
union
select getdate()-6, 'DD', 3
union
select getdate()-5, 'DD', 13
union
select getdate()-5, 'SO', 23
union
select getdate()-5, 'PO', 8
我想要的是:
mdate | paymenttype | totalpmtamt | incrtotal
2016-08-29 | DD | 10 | 10
2016-08-29 | SO | 12 | 22
2016-08-30 | DD | 3 | 25
2016-08-31 | DD | 13 | 38
2016-08-31 | SO | 8 | 46
2016-08-31 | PO | 23 | 69
我已经尝试将我在这里找到的其他代码改编成:
select t1.mdate,
t1.pmttype,
t1.totalpmtamt,
SUM(t2.totalpmtamt) as runningsum
from #testdata t1
join #testdata t2 on t1.mdate >= t2.mdate and t1.pmttype >= t2.pmttype
group by t1.mdate, t1.pmttype, t1.totalpmtamt
order by t1.mdate
但我得到的只是
mdate | paymenttype | totalpmtamt | incrtotal
2016-08-29 | DD | 10 | 10
2016-08-29 | SO | 12 | 22
2016-08-30 | DD | 3 | 13
2016-08-31 | DD | 13 | 26
2016-08-31 | SO | 8 | 34
2016-08-31 | PO | 23 | 69
有人可以帮忙吗?
【问题讨论】:
-
用您正在使用的数据库标记您的问题。
-
您可以在创建示例数据时使用更简单的 VALUES (...)。
标签: sql sql-server-2012 grouping cumulative-sum