我在sql查询中遇到一个问题,这是我尝试的解决方案:
CREATE TABLE #EventTable(eStartDate datetime,eEndDate datetime)
insert into #EventTable VALUES('2014-10-21 10:57:48.603','2014-10-22 10:57:48.603')
insert into #EventTable VALUES('2014-10-23 10:57:48.603','2014-10-23 10:57:48.603')
insert into #EventTable VALUES('2014-10-25 10:57:48.603','2014-10-27 10:57:48.603')
insert into #EventTable VALUES('2014-10-28 10:57:48.603','2014-10-30 10:57:48.603')
insert into #EventTable VALUES('2014-10-31 10:57:48.603','2014-11-02 10:57:48.603')
第二张表
CREATE TABLE #NeedDateTable(StartDate datetime,EndDate datetime)
insert into #NeedDateTable VALUES('2014-10-22 10:57:48.603','2014-10-26 10:57:48.603')
insert into #NeedDateTable VALUES('2014-11-23 10:57:48.603','2014-11-23 10:57:48.603')
insert into #NeedDateTable VALUES('2014-11-02 10:57:48.603','2014-11-03 10:57:48.603')
SELECT * from #EventTable
SELECT * from #NeedDateTable
我想从#NeedDateTable返回与#EventTable重叠的日期。所以在我的情况下它应该返回两个日期“ 2014-10-22 10:57:48.603 && 2014-10-26 10:57:48.603 ”和 “ 2014-11-02 10:57:48.603 && 2014-11-03 10:57:48.603 ”
这是我的查询
SELECT Startdate , EndDate
FROM #NeedDateTable a,#EventTable b
WHERE ((a.Startdate <= b.eStartDate and b.eStartDate<= a.EndDate)
OR (a.Startdate <= b.eEndDate and b.eEndDate <= a.EndDate))
它返回上述日期的重复记录。你能帮我解决一下我的问题。
答案 0 :(得分:2)
SELECT a.StartDate,a.EndDate
FROM NeedDateTable a
INNER JOIN
EventTable b
ON a.StartDate=b.eStartDate
OR a.StartDate=b.eEndDate
OR a.EndDate=b.eStartDate
OR a.EndDate=b.eEndDate;
答案 1 :(得分:1)
我在你输出中看到你想要有StartDate = EventTable的eEndDate的NeedDateTable记录。如果是这种情况,那么这里是查询:
select a.* from NeedDateTable a join EventTable b
on a.StartDate = b.eEndDate;
如果你想返回NeedDateTable的记录,其中存在一个记录在EventTable中,其estartdate或eenddate位于NeedDateTable的startdate和end date之间,那么:
select * from NeedDateTable a
where exists
(
select 1 from EventTable b
where (b.eStartDate between a.StartDate and a.EndDate) or
(b.eEndDate between a.StartDate and a.EndDate)
);
答案 2 :(得分:1)
尝试将其添加到测试表中:
insert into #EventTable VALUES('2015-05-10','2015-05-10')
insert into #EventTable VALUES('2016-05-10','2016-05-13')
insert into #NeedDateTable VALUES('2015-05-10','2015-05-10')
insert into #NeedDateTable VALUES('2016-05-11','2016-05-12')
两个示例都会重叠,但其他答案目前无法确定其中一个重叠。
以下是检测重叠的方法:
SELECT * FROM #NeedDateTable a
WHERE exists
(
SELECT null FROM #EventTable b
WHERE
a.StartDate <= b.eEndDate and
a.EndDate >= b.eStartDate
);
答案 3 :(得分:0)
在查询中使用Simple Between语句
SELECT Startdate,
EndDate
FROM #NeedDateTable a cross join
#EventTable b
WHERE a.Startdate BETWEEN b.eStartdate AND b.eEndDate
OR a.EndDate BETWEEN b.eStartdate AND b.eEndDate