簡體   English   中英

在SQL Server 2012中減去上一行的值

[英]To subtract a previous row value in SQL Server 2012

這是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;

誰能幫我?

與列一起使用order by以獲得一致的結果。

使用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;

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM