计算运行总列的总和

时间:2014-06-13 05:25:27

标签: sql sql-server-2008

我正在运行特定列的总数,但现在我需要得到运行总列的总和

id     somedate    somevalue  runningtotal   sumofrunning total
--     --------    ---------  ------------   ------------------ 
45     01/Jan/09   3          3                    138 
23     08/Jan/09   5          8                    138
12     02/Feb/09   0          8                    138   
77     14/Feb/09   7          15                   138 
39     20/Feb/09   34         49                   138  
33     02/Mar/09   6          55                   138 

3 个答案:

答案 0 :(得分:0)

请尝试:

select
    *,
    SUM(RunningTotal) OVER() SumOfRunningTotal
from
    YourTable

答案 1 :(得分:0)

将查询结果存储在临时表中。

select ....
into # T
from ...

计算变量的和值。

declare @sum bigint;

select sum(runningtotal)
from #T;

最后对临时表进行查询。

select *, @sum as [sumofrunning total]
from #T

另一种方法是对现有查询执行派生表,并在主查询中使用sum() over()

select T.*, sum(T.runningtotal) over() as [sumofrunning total]
from (
     -- your query goes here
     select ...
     from ...
     )

答案 2 :(得分:0)

试试这个(UGLY和SLOW),但似乎有效,

WITH somecte (id, somedate, somevalue, runningtotal, somegroupe )
AS
(
    SELECT 
      a.id,
      a.somedate,
      a.somevalue,
      -- Here goes your running total logic
      (SELECT SUM(b.somevalue)
                   FROM   sometable b
                   WHERE  b.somedate <= a.somedate) AS runningtotal,
      1 as somegroupe 

    FROM sometable a
  )


SELECT id, somedate, somevalue, runningtotal,
       (SELECT SUM(runningtotal)
        FROM somecte
        GROUP BY somegroupe) AS sumofrunningtotal

FROM somecte

检查SQLFiddle