累积汇总列

时间:2012-12-13 14:54:53

标签: sql

我可能需要一些SQL语句的帮助。所以我有“cont”表,看起来像这样:

cont_id     name       weight
----------- ---------- -----------
1           1          10
2           1          20
3           2          40
4           2          15
5           2          20
6           3          15
7           3          40
8           4          60
9           5          10
10          6          5

然后我总结了权重列并按名称对其进行了分组:

name       wsum
---------- -----------
2          75
4          60
3          55
1          30
5          10
6          5

结果应该有一个累积的列,看起来应该是这样的:

name       wsum        acc_wsum
---------- ----------- ------------
2          75          75
4          60          135
3          55          190
1          30          220
5          10          230
6          5           235

但我没有设法让最后一个声明有效......

编辑:本声明做到了(感谢戈登)

select t.*,
    (select sum(wsum) from (select name, SUM(weight) wsum
    from cont
    group by name)
    t2 where t2.wsum > t.wsum or (t2.wsum = t.wsum and t2.name <= t.name)) as acc_wsum
from (select name, SUM(weight) wsum
from cont
group by name) t
order by wsum desc

2 个答案:

答案 0 :(得分:6)

所以,最好的方法是使用累积和:

select t.*,
       sum(wsum) over (order by wsum desc) as acc_wsum
from (<your summarized query>) t

order by子句使此累积。

如果您没有该功能(在SQL Server 2012和Oracle中),相关子查询是一种简单的方法,假设求和权重是不同的值:

select t.*,
       (select sum(wsum) from (<your summarized query>) t2 where t2.wsum >= t.wsum) as acc_wsum
from (<your summarized query>) t

这应该适用于SQL的所有方言。要处理累积权重可能重复的情况:

select t.*,
       (select sum(wsum) from (<your summarized query>) t2 where t2.wsum > t.wsum or (t2.wsum = t.wsum and t2.name <= t.name) as acc_wsum
from (<your summarized query>) t

答案 1 :(得分:0)

试试这个

;WITH CTE
AS
(
 SELECT *,
ROW_NUMBER() OVER(ORDER BY wsum) rownum
FROM @table1
 ) 
 SELECT 
 c1.name, 
 c1.wsum,
 acc_wsum= (SELECT SUM(c2.wsum) 
                   FROM cte c2
                   WHERE c2.rownum <= c1.rownum)
 FROM CTE c1;

或者您可以加入而不是使用子查询

;WITH CTE
AS
(
 SELECT *,
ROW_NUMBER() OVER(ORDER BY usercount) rownum
 FROM @table1
) 
 SELECT 
 c1.name, 
 c1.wsum,
 acc_wsum= SUM(c2.wsum) 
 FROM CTE c1
 INNER JOIN CTE c2 ON c2.rownum <= c1.rownum
 GROUP BY c1.name, c1.wsum;