0

我有以下表格的表格

id  First service date  Last service date
1   6/19/2006           6/19/2006
1   7/3/2006            7/3/2006
1   7/19/2006           7/19/2006
1   9/10/2007           9/10/2007
1   9/25/2007           9/25/2007
2   4/3/2007            4/3/2007
2   7/9/2007            7/9/2007
2   10/1/2007           5/19/2008
2   1/15/2008           1/15/2008
2   2/13/2008           2/13/2008
2   3/7/2008            3/7/2008
3   5/9/2006            5/9/2006
3   5/15/2006           5/15/2006
3   6/22/2006           6/22/2006
3   10/3/2006           10/3/2006

我需要找到每个 id 的最短服务日期和最长服务日期。施加的条件是,如果每次服务之间的间隔超过 90 天,那么最近的第一次服务日期将是最短服务日期。

所以我期待的结果是

ID  Minimum date of service     Max date of service
1   9/10/2007                   9/25/2007
2   7/9/2007                    5/19/2008
3   10/3/2006                   10/3/2006
4

1 回答 1

1

I think this will give you what you want:

select t1.id, min(t2.firstdate), max(t2.lastdate)
from yourTable t1
inner join yourTable t2
    on t1.id = t2.id
    and datediff(day, t1.firstdate, t2.firstdate) > 90
group by t1.id

See SQL Fiddle with Demo

于 2012-08-15T15:29:56.537 回答