的順序排列日期範圍在這裏,我需要按照usr_id順序排列日期範圍。如何按照sql
CREATE TABLE #temp(st_date DATE,end_date DATE,usr_id INT)
INSERT #temp
VALUES ('2007-03-01 ','2015-01-31 ',1),
('2015-02-01 ','2015-05-05 ',1),
('2015-05-06 ','2017-04-01 ',1),
('2007-03-01 ','2014-01-31 ',2),
('2007-03-01 ','2015-01-31 ',3),
('2015-02-01 ','2017-04-01 ',3),
('2020-02-01 ','2020-06-05 ',1),
('2020-06-06 ','2020-08-08 ',1)
SELECT t2.st_date,t1.end_date,t1.usr_id FROM #temp t1 ,#temp t2
WHERE t1.st_date = dateadd(dd,+1,t2.end_date) AND t2.usr_id = t1.usr_id
DROP TABLE #temp
我的答案應該是這樣的。
st_date end_date usr_id
2007-03-01 2017-04-01 1
2020-02-01 2020-08-08 1
2007-03-01 2017-04-01 3
2007-03-01 2014-01-31 2
起初我以爲這和訂單一樣簡單,但我認爲你真正想要的是將相鄰日期的島嶼分組。這裏有一篇來自Jeff Moden的文章,解釋瞭如何做到這一點。 http://www.sqlservercentral.com/articles/T-SQL/71550/ –