首页 > 代码库 > T-SQL 运用自连接逐行统计sum值

T-SQL 运用自连接逐行统计sum值

主要是利用聚合函数通过自连接去实现分组逐行计算某列的sum值

这是统计前

统计后结果为

 

实现代码如下:

 1 create table sales 2 (  3   productname nvarchar(50)  4  ,dateofmonth nvarchar(20) 5  ,quantity int  6 ) 7  8 insert into sales 9 select p1,201401,10010 union all 11 select p1,201402,30012 union all 13 select p1,201403,50014 union all 15 select p2,201401,20016 union all 17 select p2,201402,30018 union all 19 select p2,201403,30020 union all 21 select p2,201401,30022 union all 23 select p3,201402,10024 union all 25 select p3,201403,30026 27 --select * from sales28 29 select ROW_NUMBER()over(order by productname,dateofmonth,quantity) sid,*30 into #temp31 from sales32 33 --select * from #temp34 select dense_rank()over(order by productname) rid,*35 into #temp136 from #temp37 38 select39  a.productname40 ,a.dateofmonth41 ,a.quantity42 ,sum(b.Quantity) AS TOTAL43 from #temp1 a,#temp1 b44 where a.sid >= b.sid and a.rid = b.rid45 group by a.productname,a.dateofmonth,a.quantity

 

T-SQL 运用自连接逐行统计sum值