Accumulate a summarized column

后端 未结 2 1809
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 07:37

I could need some help with a SQL statement. So I have the table \"cont\" which looks like that:

cont_id     name       weight
----------- ---------- -------         


        
相关标签:
2条回答
  • 2021-01-18 07:52

    try this

    ;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;
    

    or you can join instead of using subquery

    ;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;
    
    0 讨论(0)
  • 2021-01-18 08:08

    So, the best way to do this is using cumulative sum:

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

    The order by clause makes this cumulative.

    If you don't have that capability (in SQL Server 2012 and Oracle), a correlated subquery is an easy way to do it, assuming the summed weights are distinct values:

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

    This should work in all dialects of SQL. To work with situations where the accumulated weights might have duplicates:

    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
    
    0 讨论(0)
提交回复
热议问题