当前位置: 代码迷 >> Sql Server >> 如其查询多条数据间的时间重合段
  详细解决方案

如其查询多条数据间的时间重合段

热度:32   发布时间:2016-04-24 09:38:13.0
如果查询多条数据间的时间重合段?
本帖最后由 hechengmiao 于 2014-12-03 17:46:53 编辑
有如下表:
name    startdate             enddate
a             2014-11-01       20141105
b             2014-11-02       20141108
c             2014-11-06       20141110
d             2014-11-03       20141104
e             2014-11-11       20141113


希望能够查询到的结果如下:
a             2014-11-01       20141105
b             2014-11-02       20141108
c             2014-11-06       20141110
d             2014-11-03       20141104

因为a、b、c、d四行有时间重合。
请问如何能够实现以上的查询,用一段查询语句可以,用函数实现也可以。
------解决思路----------------------
SELECT * FROM TB T WHERE EXISTS
    (SELECT 1 FROM TB WHERE T.name<>name AND T.startdate<=enddate AND T.enddate>=startdate)

------解决思路----------------------
查詢的數據的startdate大於或等於其他數據的startdate,且小於或等於其他數據的enddate
或者
查詢的數據的enddate大於或等於其他數據的startdate,且小於或等於其他數據的enddate

create table tbl
(
name varchar(10),
startdate date,
enddate varchar(10)
)
insert tbl values
             ('a','2014-11-01','20141105'),
             ('b','2014-11-02','20141108'),
             ('c','2014-11-06','20141110'),
             ('d','2014-11-03','20141104'),
             ('e','2014-11-11','20141113')
select * from tbl as a
where exists(select 1 from tbl where name!=a.name and 
(a.startdate between startdate and enddate or 
a.enddate between startdate and enddate))  
  相关解决方案