SQL在两个日期之间比较多行中的一个日期

SQL在两个日期之间比较多行中的一个日期,sql,sql-server,sql-server-2012,Sql,Sql Server,Sql Server 2012,我有两个带有公共标识符列的表。 比较第一个tab1和tab2,并需要不在tab2之间的日期的结果 Create table #tab1(id int, Idvalue int, IDDate date) insert into #tab1 select 1,1, '2013-06-25' UNION ALL select 2,1, '2014-11-28' union all select 3,1, '2015-12-06' union all select 4,1, '2013-04-08

我有两个带有公共标识符列的表。 比较第一个tab1和tab2,并需要不在tab2之间的日期的结果

Create  table #tab1(id int, Idvalue int, IDDate date)
insert into #tab1
select 1,1, '2013-06-25' UNION ALL 
select 2,1, '2014-11-28' union all
select 3,1, '2015-12-06' union all
select 4,1, '2013-04-08' union all
select 5,1, '2051-12-12'
Select * from #tab1


Create  table #tab2(Idvalue int, Startdate date, EndDate Date)
insert into #tab2
select 1, '2013-05-01','2013-12-31' UNION ALL 
select 1, '2014-06-01','2050-01-01'

Select * from #tab2

DROP table #tab1
DROP table #tab2
结果:

4   1   2013-04-08
5   1   2051-12-12
尝试左连接

select * from tab1 left join tab2 on IDDate between Startdate and enddate
where Idvalue is null

不存在以下版本:

select *
from #tab1
where not exists
(
    select 1
    from #tab2
    where #tab1.IDDate between #tab2.Startdate and #tab2.EndDate
)

我不确定,但你可以加入

SELECT * 
FROM   tab1 
       LEFT JOIN tab2 
              ON tab1.idvalue = tab2.idvalue 
                 AND tan1.iddate > tab2.start 
                 AND tab1.iddate < tab2.end 
选择*
从表1开始
左连接选项卡2
在tab1.idvalue=tab2.idvalue上
和tan1.iddate>tab2.start
和tab1.iddate

希望对您有所帮助

这应该可以工作,或者可能需要对_Data_范围内的列进行一些额外的筛选:

SELECT *
    ,CASE 
        WHEN IDDate BETWEEN StartDate
                AND EndDate
            THEN 'YES'
        ELSE 'NO'
        END AS IN_Data_Range
FROM #tab1
CROSS APPLY #tab2

您正在使用哪个数据库?SQL Server 2012