我有以下两列。
Date | Market Value
------------------------------
2016-09-08 | 100
2016-09-07 | 130
2016-09-06 | 140
2016-09-05 | 180
我想添加一个列,用于计算两个日期之间Market Value
的差异。
Date | Market Value | Delta
------------------------------------------
2016-09-08 | 100 | -30
2016-09-07 | 130 | -10
2016-09-06 | 140 | -40
2016-09-05 | 180 |
100 (2016-09-08) minus 130 (2016-09-07) = -30
我该如何编写该功能?
答案 0 :(得分:3)
在SQL Server 2012+中,最有效和最简单的方法是使用内置的LEAD
函数。
SELECT
[Date]
,[Market Value]
,LEAD([Market Value]) OVER (ORDER BY [Date] DESC) - [Market Value] AS Delta
FROM YourTable
;
LEAD
返回其ORDER BY
子句指定的下一行的值。
自我加入表格的所有其他方法效率较低。
答案 1 :(得分:0)
对于2012年以下的SQL-Server,你可以试试这个:
with cte as
(SELECT
ROW_NUMBER() OVER (ORDER BY [Date] DESC) row,
[Date],
[Market Value]
FROM [YourTable])
SELECT
a.[Date] ,
b.[Market Value] - ISNULL(a.[Market Value],0) AS Delta
FROM
cte a
LEFT JOIN cte b
on a.row = b.row+1
原始帖子来自此处:SQL difference between rows 对于SQL-Server 2012及更高版本,您可以使用推荐的LEAD-Function。
答案 2 :(得分:0)
如果你有连续约会,你可以
select t1.date, t1.market_value, t1.market_value-t2.market_value from data_table t1 left join data_table t2 on t1.date-1=t2.date
如果你没有连续的约会并且想要计算星期一和星期五之间的差异,你可以使用rownum这样的例子
select t1.date, t1.market_value, t1.market_value-t2.market_value from (select rownum, date,market_value from data_table) t1 left join (select rownum, date,market_value from data_table) t2 on t1.rownum-1=t2.rownum
答案 3 :(得分:0)
CREATE PROCEDURE UPDATE_DELTA
@START_DATE DATETIME,
@END_DATE DATETIME
AS BEGIN
UPDATE T
SET DELTA = MARKET_VALUE - (SELECT MARKET_VALUE
FROM YOURTABLE
WHERE [DATE] = T.[DATE] - 1)
FROM YOURTABLE T
WHERE [DATE] BETWEEN @START_DATE AND @END_DATE
END
然后执行:
EXEC UPDATE_DELTA '2016-09-05', '2016-09-08'
只要您对日期进行了排序,这就有效。
答案 4 :(得分:0)
添加列并按以下方式更新:
UPDATE t SET t.Delta = t.Market_Value-t2.Market_Value
FROM yourtable t
INNER JOIN yourtable t2 ON DATEADD(DD,-1,t.Date) = t2.Date