我在同一列中有两个日期,我需要减去它们之间的天数/小时数。
SELECT [ID],[DATA] FROM [DADOS]
我想像这样显示:
ID Date DiffDate
1 2017-05-12 0
2 2017-05-14 2
3 2017-05-28 14
答案 0 :(得分:2)
在使用SQL Server 2008时,需要在同一表上使用LEFT JOIN
:
WITH VTE AS (
SELECT ID,
CONVERT(date, [date]) AS [date] --That's not confusing
FROM (VALUES(1,'20170512'),
(2,'20170514'),
(3,'20170528')) V(ID, [date]))
SELECT V1.ID,
V1.[date],
ISNULL(DATEDIFF(DAY,V2.[date],V1.[date]),0) AS DiffDate
FROM VTE V1
LEFT JOIN VTE V2 ON V1.ID -1 = V2.ID;
但是,如果您有SQL Server 2012+,则可以使用LAG
轻松实现这一点,这意味着您无需扫描表两次:
WITH VTE AS (
SELECT ID,
CONVERT(date, [date]) AS [date] --That's not confusing
FROM (VALUES(1,'20170512'),
(2,'20170514'),
(3,'20170528')) V(ID, [date]))
SELECT V.ID,
V.[date],
ISNULL(DATEDIFF(DAY,LAG(V.[date]) OVER (ORDER BY V.ID),V.[date]),0) AS DiffDate
FROM VTE V;
答案 1 :(得分:0)
对于旧版本的SQL Server 您应该使用如下查询
SELECT
d1.[ID],
d1.[DATA],
DiffDate=DATEDIFF(d,ISNULL(d2.[Data],d1.[Data]),d1.[Data])
FROM [DADOS] d1
LEFT JOIN [DADOS] d2
ON d1.[id]=d2.[id]+1
如果您的SQL Server版本支持以下功能,则可以 LEAD/LAG 功能
SELECT
[ID],
[DATA],
DiffDate=DATEDIFF(d,ISNULL(LAG([Data]) over( order by [Id]),[Data]),[Data])
FROM [DADOS]
请注意,ISNULL用于处理第一行的0值
答案 2 :(得分:0)
SQL Server 2008不支持LAG()
,而这正是您真正需要的。我建议使用OUTER APPLY
:
SELECT d.*,
COALESCE(DATEDIFF(day, dprev.DATA, d.DATA), 0)
FROM DADOS d OUTER APPLY
(SELECT TOP (1) d2.*
FROM DADOS d2
WHERE d2.DATA < d.DATA
ORDER BY DATA DESC
) dprev;