如何按范围运行总计?

时间:2015-02-06 08:12:44

标签: sql-server tsql sql-server-2008-r2

如何根据范围获得运行总计:

name, Level, value, runningtotal;
A             5      5;
B     1       3     10;
B     2       2     10;
C             1     11;

2 个答案:

答案 0 :(得分:0)

我无法告诉您在运行总计的列上。但在2008年,做总计的最佳方式是这样的自我加入:

CREATE TABLE #Test(
    ID      INT NOT NULL PRIMARY KEY,
    AValue  INT NOT NULL)

INSERT INTO #Test VALUES (1,4), (2,2), (3,18)

SELECT T1.ID, T1.AValue, SUM(T2.AValue) RunningTotal
FROM #Test T1
JOIN #Test T2 ON T1.ID >= T2.ID
GROUP BY T1.ID, T1.AValue

DROP TABLE #Test

答案 1 :(得分:0)

with cte(name,value) as
(
select name,sum(value) as val from A group by name
)
,
    cte2 as
    (
    SELECT c.name,SUM(b.value) as val
    FROM   cte c inner join
           cte b
    on b.name <= c.name
    GROUP BY c.name
    )
    select c.name,c.value,b.val from A c inner join cte2 b on c.name=b.name 
    order by c.name