我仍然是我的英语的新手和借口。您会看到我有两个不同时期的人,如果他们是连续的,我想聚合这些时期。我不知道如何使用例如与下一行或前一行相关的min()
and函数来比较日期。max()
还是有更简单的方法来解决这个问题?我只有没有滞后和领先功能的 SQL Server 2008 R2。
样本数据:
DECLARE @Table TABLE(
PersonID INT,
FROM date,
TO date
)
INSERT INTO @Table SELECT 1,'2011-01-01','2011-04-30'
INSERT INTO @Table SELECT 1,'2011-05-01','2011-08-31'
INSERT INTO @Table SELECT 1,'2011-09-01','2011-12-31'
INSERT INTO @Table SELECT 1,'2012-01-01','2012-03-31'
INSERT INTO @Table SELECT 2,'2011-03-01','2011-06-30'
INSERT INTO @Table SELECT 2,'2011-07-01','2011-10-31'
INSERT INTO @Table SELECT 2,'2013-01-01','2013-04-30'
INSERT INTO @Table SELECT 2,'2013-05-01','2013-08-31'
我期待这样的事情,尤其是在 PersonID 2 上:
PersonID FROM TO
1 , 2011-01-01 , 2012-03-31
2 , 2011-03-01 , 2011-10-31
2 , 2013-01-01 , 2013-08-31