我在SQL中有一个表,其中一列包含大量IDS,其中一些是重复的,第二列包含许多不同的日期
我想创建一个表格,其中我在表格的左侧有一个唯一的IDS列表,一列称为天数,然后在表格中显示最后一个日期和倒数第二个日期之间的天数在桌子上。
答案 0 :(得分:2)
将Row_Number()与条件聚合一起使用。
示例强>
Declare @YourTable Table ([ID] varchar(50),[DateCol] date)
Insert Into @YourTable Values
(1,'2017-05-01')
,(1,'2017-05-05')
,(1,'2017-05-10') -- 2nd
,(1,'2017-05-31') -- Lst 21 days
,(2,'2017-05-01')
,(2,'2017-06-05')
,(2,'2017-06-10') -- 2nd
,(2,'2017-07-31') -- Lst 51 days
Select ID
,Days = DateDiff(DAY,max(case when RN=2 then DateCol end),max(case when RN=1 then DateCol end))
From (
Select *
,RN = Row_Number() over (Partition By ID Order by DateCol Desc)
from @YourTable
) A
Group By ID
<强>返回强>
ID Days
1 21
2 51
答案 1 :(得分:1)
这里我将MAX(DateCol)小于具有相同ID的子查询MAX(DateCol) - 这在DateDiff中使用。
SELECT dT.ID
,(SELECT MAX(DateCol)
FROM @YourTable Y
WHERE Y.DateCol < dT.MaxDateCol --Date less than MAX
AND Y.ID = dT.ID
) AS [Date less than MAX] --added by request
,dT.MaxDateCol AS [Max Date] --added by request
,DATEDIFF(DAY, (SELECT MAX(DateCol)
FROM @YourTable Y
WHERE Y.DateCol < dT.MaxDateCol --Date less than MAX
AND Y.ID = dT.ID
)
, dT.MaxDateCol
) AS [Days Difference] --datediff between max and date less than MAX
FROM (
SELECT ID
,MAX([DateCol]) [MaxDateCol] --MAX, removes duplicate ID's.
FROM @YourTable
GROUP BY ID
) AS dT