我有一张这样的表
ID firSrvdate LastSrvdate
----------------------
1 1-12-81 1-15-81
1 1-18-81 1-18-81
1 2-9-81 3-1-81
2 4-2-81 4-5-81
2 8-18-81 8-18-81
2 11-9-81 11-21-81
3 3-12-81 4-15-81
3 7-17-81 8-19-81
我需要在服务之间的差异小于90天的条件下为每个Mindate
找到Maxdate
和ID
所以我期待的结果是这样的
ID Mindate MaxDate
-----------
1 1-12-81 3-1-81
2 8-18-81 11-21-81
3 7-17-81 8-19-81
答案 0 :(得分:2)
由于我们不确定哪一对日期适合90天的窗口,我们首先需要自己加入。一旦我们有了,我们必须选择我们想要的那个。使用row_Number,我们可以按最大的差异排序。我也使用maxdate作为平局。这是intermediate result looks like
的内容SELECT id,
mindate,
maxdate
FROM (SELECT t1.id,
t1.mindate,
t2.maxdate,
Row_number() OVER (partition BY t1.ID
ORDER BY Datediff(day, t1.mindate,
t2.maxdate) DESC, t2.maxdate DESC) rn
FROM table1 t1
INNER JOIN table1 t2
ON t1.id = t2.id
WHERE Datediff(day, t1.mindate, t2.maxdate) < 90) AS t
WHERE rn = 1
答案 1 :(得分:1)
您可以使用having子句来完成此操作:
select id, min(date) as mindate, max(date) as maxdate
from table
group by id
having datediff(day, min(date), max(date) < 90