在SQL Server 2012中减去上一行值

时间:2017-02-14 20:04:36

标签: sql sql-server

这是SQL查询

SELECT 
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)) [Sno], 
    _Date, 
    SUM(Payment) Payment 
FROM 
    DailyPaymentSummary 
GROUP BY
    _Date
ORDER BY
    _Date

这会返回这样的输出

Sno _Date       Payment
---------------------------
1   2017-02-02   46745.80
2   2017-02-03  100101.03
3   2017-02-06  140436.17
4   2017-02-07  159251.87
5   2017-02-08  258807.51
6   2017-02-09  510986.79
7   2017-02-10  557399.09
8   2017-02-13  751405.89
9   2017-02-14  900914.45

如何获得如下所示的附加列

Sno _Date       Payment     Diff
--------------------------------------
1   02/02/2017   46745.80    46745.80
2   02/03/2017  100101.03    53355.23
3   02/06/2017  140436.17    40335.14
4   02/07/2017  159251.87    18815.70
5   02/08/2017  258807.51    99555.64
6   02/09/2017  510986.79   252179.28
7   02/10/2017  557399.09    46412.30
8   02/13/2017  751405.89   194006.80
9   02/14/2017  900914.45   149508.56

我尝试过以下查询,但无法解决错误

WITH cte AS
(
    SELECT  
        ROW_NUMBER() OVER (ORDER BY (SELECT 1)) [Sno], 
        _Date, 
        SUM(Payment) Payment
    FROM 
        DailyPaymentSummary 
    GROUP BY
        _Date
    ORDER BY
        _Date
)
SELECT
    t.Payment, 
    t.Payment - COALESCE(tprev.col, 0) AS diff
FROM
    DailyPaymentSummary t 
LEFT OUTER JOIN
    t tprev ON t.seqnum = tprev.seqnum + 1;

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:3)

使用带有列的订单来获得一致的结果。

使用lag函数从前一行获取数据并按以下方式进行减法:

with t
as (
    select ROW_NUMBER() over (order by _date) [Sno],
        _Date,
        sum(Payment) Payment
    from DailyPaymentSummary
    group by _date
    )
select *,
    Payment - lag(Payment, 1, 0) over (order by [Sno]) diff
from t;

答案 1 :(得分:1)

您可以使用lag()获取上一行值

coalesce(lag(sum_payment_col) OVER (ORDER BY (SELECT 1)),0)