SQL Server:扣除相邻列组

时间:2015-02-28 18:43:52

标签: sql sql-server reporting-services view

背后的逻辑是,我正在使用SSRS开发报告。我面临的问题是,在一张桌子上我有一个金额字段(在这种情况下是一列),而在另一张桌子上我有金额要扣除(在这种情况下是B列)。

当我在报告(ssrs)上显示此记录时,它显示为以下(第一个表),但他们正在寻找的输出是第二个。

工作原理:A列是A-B(6.000 - 2.000)的结果,但第一列除外,此结果(6.000 - 2.000 = 4.000)将在A上设置。

我现在拥有的:

id  A       B       
-----------------
1   6.000   2.000   
2   6.000   1.000   
3   6.000   2.000   
4   6.000   1.000   

预期输出

id  A       B       C
-------------------------
1   6.000   2.000   4.000 
2   4.000   1.000   3.000
3   3.000   2.000   1.000
4   1.000   1.000   0.000

1 个答案:

答案 0 :(得分:0)

这应该有效。我已经添加了ROW_NUMBER,以防ID之间存在差距。如果不是 - 只需忽略它并在此场景中使用您的id字段。

DECLARE @data TABLE
(
    id INT
    , A FLOAT
    , B FLOAT
);

INSERT INTO @data
    (id, A, B)
VALUES
      (1, 6.000, 2.000)
    , (2, 6.000, 1.000)
    , (3, 6.000, 2.000)
    , (4, 6.000, 1.000)
    , (6, 5.000, 1.000);

;WITH ordered (rn, id, A, B)
AS (
    SELECT ROW_NUMBER() OVER(ORDER BY id) AS rn, id, A, B
    FROM @data
),
cte
AS (
    SELECT rn, id, A, B, A-B AS C
    FROM ordered
    WHERE rn = 1

    UNION ALL

    SELECT T.rn, T.id, C.C, T.B, C.C - T.B
    FROM ordered AS T
    INNER JOIN cte AS C
        ON c.rn + 1 = T.rn
)
SELECT *
FROM cte

使用分析函数的其他示例:

;WITH ordered (previous_id, id, A, B)
AS (
    SELECT LAG(id) OVER(ORDER BY id) , id, A, B
    FROM @data
),
cte
AS (
    SELECT previous_id, id, A, B, A-B AS C
    FROM ordered
    WHERE previous_id IS NULL

    UNION ALL

    SELECT T.previous_id, T.id, C.C, T.B, C.C - T.B
    FROM ordered AS T
    INNER JOIN cte AS C
        ON c.id = T.previous_id
)
SELECT id, A, B, C
FROM cte

<强>输出:

rn  id  A   B   C
------------------
1   1   6   2   4
2   2   4   1   3
3   3   3   2   1
4   4   1   1   0
5   6   0   1   -1