SQL:如何从给定的一组日期范围中找到唯一的日期范围?

时间:2016-03-04 18:30:22

标签: sql sql-server date

我有一个用户表及其日期范围,采用INT格式(yyyymmdd),如下所示:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<button onclick="document.execCommand('justifyCenter', false, null);">center</button>

<div contenteditable="true" style="border:1px solid gray;"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco <br><br>laboris nisi ut<br><br><br> aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></div>


</body>
</html>

我需要为每个用户找到连续的唯一日期范围(没有任何重复)。输出应该是这样的

Id  Name    StartDate   EndDate
1   abc     20160216    20160217
1   abc     20160228    20160228
1   abc     20160301    20160301
1   abc     20160301    20160302
1   abc     20160301    20170401
1   abc     20160302    20160302
1   abc     20160303    20160303
1   abc     20160303    20170401
3   def     20160217    20160217
3   def     20160218    20160229
3   def     20160218    20160229
3   def     20160225    20160225
3   def     20160229    20160229
3   def     20160302    20160302

使用此脚本,您可以创建表格:

 Id Name    StartDate   EndDate
1   abc     20160216    20160217
1   abc     20160228    20160228
1   abc     20160301    20170401
3   def     20160217    20160229
3   def     20160302    20160302

编辑: 简而言之,如果我有这样的数据

CREATE TABLE #data
(
 Id INT,
 Name VARCHAR(50),
 StartDate INT,
 EndDate INT,
)
INSERT INTO #data VALUES(1,'abc',20160216,20160217)
INSERT INTO #data VALUES(1,'abc',20160228,20160228)
INSERT INTO #data VALUES(1,'abc',20160301,20160301)
INSERT INTO #data VALUES(1,'abc',20160301,20160302)
INSERT INTO #data VALUES(1,'abc',20160301,20170401)
INSERT INTO #data VALUES(1,'abc',20160302,20160302)
INSERT INTO #data VALUES(1,'abc',20160303,20160303)
INSERT INTO #data VALUES(1,'abc',20160303,20170401)
INSERT INTO #data VALUES(3,'def',20160217,20160217)
INSERT INTO #data VALUES(3,'def',20160218,20160229)
INSERT INTO #data VALUES(3,'def',20160218,20160229)
INSERT INTO #data VALUES(3,'def',20160225,20160225)
INSERT INTO #data VALUES(3,'def',20160229,20160229)
INSERT INTO #data VALUES(3,'def',20160302,20160302)

我需要输出如下。

Id  Name    StartDate   EndDate
1   abc     20160216    20160217
**1 abc     20160301    20160302
1   abc     20160301    20160303**

2 个答案:

答案 0 :(得分:1)

猜猜你我需要使用SELECT DISTINCT,它只搜索表格列中的唯一值。

这就是你要找的东西吗?我没有得到你想要的输出......

答案 1 :(得分:1)

您应该能够连接StartDate和EndDate,并查找连接的值是不同的。

select id, StartDate, EndDate, distinct(contactDate) from (Select id, StartDate, EndDate, CONCAT_WS('', StartDate, EndDate) AS concatDate from Data)

修改

实际上我认为你可以在没有结束的情况下做到这一点......

Select id, StartDate, EndDate, distinct(StartDate, EndDate) from data