SQL-尝试从同一列中减去日期值

时间:2016-02-11 19:33:08

标签: sql sql-server sql-server-2008-r2

我需要将最大日期减去上一个上一个状态日期,但无法弄明白。我将使用FindingID和UpdatedEstimatedRemediationDate。

例如:

FindingID'FND-5645'已更新3次:

UpdatedEstimatedRemediationDate
--------------------------------
NULL
2015-06-15
2015-12-30
2016-06-30

我需要从2016年6月30日到2015年12月12日获得日差。我正在使用SQL Server 2008 R2。提前谢谢。

2 个答案:

答案 0 :(得分:4)

如果我理解正确,这基本上是一个datediff()的聚合查询:

select findingid, datediff(day, min(UpdatedEstimatedRemediationDate), max(UpdatedEstimatedRemediationDate)
from t
group by findingid;

答案 1 :(得分:1)

您可以使用ROW_NUMBER()FindingId进行分区,然后按UpdateDate desc排序,选择第一个和最后一个日期,并将日期差异化为天:

<强>设定:

-- drop table UpdatedEstimatedRemediationDate
create table UpdatedEstimatedRemediationDate
(
    FindingId INT,
    UpdateDate DATE
)

insert into UpdatedEstimatedRemediationDate values 
(1, '2015-06-15'), (1, '2015-12-30'), (1, '2016-06-30'), (2, '2015-07-13'), (2, '2016-05-01')
GO

<强>查询:

;WITH Cte AS (
    SELECT FindingId, UpdateDate, ROW_NUMBER() OVER (PARTITION BY FindingId ORDER BY UpdateDate DESC) AS RowNo
    FROM UpdatedEstimatedRemediationDate
)
SELECT LU1.FindingId, DATEDIFF(day, LU1.UpdateDate, LU2.UpdateDate) AS DaysDiff
 FROM Cte LU1
    JOIN Cte LU2 ON LU2.FindingId = LU1.FindingId AND LU1.RowNo = 2 AND LU2.RowNo = 1 

[没有自我加入版本]

对于SQL Server 2012,使用SELF JOIN函数可以避免LAG/LEAD

WITH CTE AS (
    SELECT FindingId, DATEDIFF(day, UpdateDate, LEAD(UpdateDate, 1, NULL) OVER (PARTITION BY FindingId ORDER BY UpdateDate)) DayDiff,
        ROW_NUMBER() OVER (PARTITION BY FindingId ORDER BY UpdateDate DESC) RowNo 
FROM UpdatedEstimatedRemediationDate)
SELECT CTE.FindingId, CTE.DayDiff
FROM CTE 
WHERE RowNo = 2