This is SQL Query
这是SQL查询
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?
谁能帮我?
2 个解决方案
#1
2
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;
#2
1
You can use lag() to get previous row values
您可以使用lag()来获取先前的行值
coalesce(lag(sum_payment_col) OVER (ORDER BY (SELECT 1)),0)
#1
2
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;
#2
1
You can use lag() to get previous row values
您可以使用lag()来获取先前的行值
coalesce(lag(sum_payment_col) OVER (ORDER BY (SELECT 1)),0)