简体   繁体   中英

To subtract a previous row value in SQL Server 2012

This is SQL Query

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

This returns output like this

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

How can I get the additional column like below

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

I have tried the following query but not able to solve the error

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;

Can anyone help me?

Use a order by with column(s) to get consistent results.

Use lag function to get data from previous row and do the subtraction like this:

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;

您可以使用lag()获取先前的行值

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM