比较同月的连续日期的值

时间:2017-10-03 10:24:52

标签: sql sql-server

我有一张桌子

ID Value Date
1   10   2017-10-02 02:50:04.480
2   20   2017-10-01 07:28:53.593
3   30   2017-09-30 23:59:59.000
4   40   2017-09-30 23:59:59.000
5   50   2017-09-30 02:36:07.520

我将Value与之前的日期进行比较。但是,我不需要在当月的第一天和上个月的最后一天之间比较结果。对于此表,我不需要比较2017-10-01 07:28:53.593 and 2017-09-30 23:59:59.000之间的结果如何完成?

此示例的结果表:

ID Value Date                      Diff
1   10   2017-10-02 02:50:04.480   10
2   20   2017-10-01 07:28:53.593   NULL
3   30   2017-09-30 23:59:59.000   10
4   40   2017-09-29 23:59:59.000   10
5   50   2017-09-28 02:36:07.520   NULL

2 个答案:

答案 0 :(得分:1)

您可以使用下面的查询

select *,
diff=LEAD(Value) OVER( PARTITION BY Month(Date),Year(Date) ORDER BY Date desc)-Value
from t 
order by id asc

see working demo

答案 1 :(得分:1)

你可以使用它。

SELECT * , 
    LEAD(Value) OVER( PARTITION BY DATEPART(YEAR,[Date]), DATEPART(MONTH,[Date]) ORDER BY ID ) - Value AS Diff 
FROM MyTable
ORDER BY ID