如何按组获得累积金额

时间:2015-03-02 08:22:58

标签: sql sql-server-2012 sum partition

这是理想的结果:

enter image description here

在ID = 14时,我需要使用新的cum_value重置附加值。

SQL :(小提琴:http://sqlfiddle.com/#!6/62f01/14

1 个答案:

答案 0 :(得分:0)

你不是那么远,但我尝试使用不那么复杂的查询:

DECLARE @t table(
        id int
        )

INSERT  INTO @t (id)
VALUES  (0),(1),(2),(3),(4),(5),(6),
        (7),(8),(9),(10),(11),(12),(13),
        (14),(15),(16),(17),(18),(19),
        (20),(21),(22),(23),(24),(99);

SELECT  *
        ,SUM(id)
         OVER(ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Cum_STEPID
FROM    @t
WHERE   id < 14
UNION
SELECT  *
        ,SUM(CASE WHEN id = 14 THEN 91000 ELSE id END)
         OVER(ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Cum_STEPID
FROM    @t
WHERE   id >= 14