SQL Server增量基于其他列的运行总计

时间:2018-02-06 01:32:33

标签: sql-server

尝试找到一种有效的方法来创建基于B列的C列值和基于B为1或-1的增量,当B在B为1或-1之间切换时,计数重新开始。

CREATE TABLE #T (a int, b int, c int);   
INSERT INTO #T VALUES (1, 1, 1), 
(2, 1, 2), 
(3, -1, -1), 
(4, -1, -2), 
(5, -1, -3), 
(6, -1, -4), 
(7, 1, 1), 
(8, 1, 2); 

enter image description here

谢谢!

1 个答案:

答案 0 :(得分:4)

诀窍是对列b进行分组。您可以使用从this answer获取的基本代码执行此操作。现在您需要将增量器切换为正或负。最简单的方法是将值乘以b列。例如:

SELECT 
   a,b,    
   ROW_NUMBER() OVER (PARTITION BY b, grp ORDER BY a) * b as c
FROM (SELECT T.*,
             (ROW_NUMBER() OVER (ORDER BY a) -
              ROW_NUMBER() OVER (PARTITION BY b ORDER BY a)
             ) as grp
      FROM T) T
ORDER BY a