在SQL Server中每行和每列的累计组合?

时间:2013-05-11 08:45:32

标签: sql-server sql-server-2008 sql-server-2005 crystal-reports crystal-reports-2008

我想在我的表中添加一列,例如计算Combined cumulative:

a    b    c    d        newcoulmn
50   0    0    0            50        
0    7    0    0            57
0    0    6    0            63
0    0    0   (4)           59
0    3    0    0            62
0    2    0    0            64
0    0    0   (8)           56
0    0    0   (7)           49

1 个答案:

答案 0 :(得分:1)

您需要选择a + b + c - d的总和,然后使用窗口函数ROW_NUMBER()计算此值的累积总和:

WITH CTE
AS
(
  SELECT *, a + b + c - d AS abcd,
     ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS rn
  FROM test
)
SELECT c1.a, c1.b, c1.c, c1.d, 
  COALESCE((SELECT SUM(c2.abcd)
            FROM cte AS c2
            WHERE c1.rn >= c2.rn), c1.abcd) AS newcolumn
FROM CTE AS c1;

请在此处查看:

这会给你:

|  A | B | C | D | NEWCOLUMN |
------------------------------
| 50 | 0 | 0 | 0 |        50 |
|  0 | 7 | 0 | 0 |        57 |
|  0 | 0 | 6 | 0 |        63 |
|  0 | 0 | 0 | 4 |        59 |
|  0 | 3 | 0 | 0 |        62 |
|  0 | 2 | 0 | 0 |        64 |
|  0 | 0 | 0 | 8 |        56 |
|  0 | 0 | 0 | 7 |        49 |

更新

使用您的查询,可以这样写:

WITH YourOriginalQuery
AS
(
    select plitno, A, datils, 0 AS B, 0 AS C, 0 AS D from table1 
    union all 
    select critno, 0, 0, B, 0, 0 from table2 
    union all 
    select klitno, 0, 0, 0, C, 0 from table3 
    union all 
    select bgitno, 0, 0, 0, 0, D from table4
), WITH CTE
AS
(
  SELECT *, a + b + c - d AS abcd,
     ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS rn
  FROM YourOriginalQuery
)
SELECT c1.a, c1.b, c1.c, c1.d, 
  COALESCE((SELECT SUM(c2.abcd)
            FROM cte AS c2
            WHERE c1.rn >= c2.rn), c1.abcd) AS newcolumn
FROM CTE AS c1;