如何从下表中查找总天数?我尝试使用DATEDIFF
函数,但我无法得到我的结果。
date days
-------------------------------
2017/11/10
2017/11/12
2017/11/15
天之间的差异应该是
2017/11/12-2017/11/10, 2017/11/15-2017/11/12.
答案 0 :(得分:2)
您可以使用LAG
(SQL Server 2012及更高版本):
CREATE TABLE t(d DATE);
INSERT INTO t(d)VALUES ('2017-11-10'), ('2017-11-12'), ('2017-11-15');
SELECT *, DATEDIFF(day, LAG(d) OVER(ORDER BY d ASC),d)
FROM t;
<强> Rextester Demo 强>
对于SQL Server 2005,您可以使用:
SELECT s.*, DATEDIFF(day, s2.d, s.d) AS days
FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY d) AS rn FROM t) s
LEFT JOIN (SELECT *, ROW_NUMBER() OVER(ORDER BY d) AS rn FROM t) s2
ON s.rn = s2.rn+1;
<强> Rextester Demo2 强>