如何按组获取累计和
How to get cumulative sum by group
这是想要的结果:
在 ID=14 时,我需要用新 cum_value
重新设置附加值。
SQL : (fiddle : http://sqlfiddle.com/#!6/62f01/14)
到目前为止你还没有,但我已经尝试了不那么复杂的查询:
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
这是想要的结果:
在 ID=14 时,我需要用新 cum_value
重新设置附加值。
SQL : (fiddle : http://sqlfiddle.com/#!6/62f01/14)
到目前为止你还没有,但我已经尝试了不那么复杂的查询:
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