首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求最有效的时间段包孕语句,所有分都送上

2013-06-26 
求最有效的时间段包含语句,所有分都送上drop table #adrop table #bcreate table #a( dt1 datetime,dt2 da

求最有效的时间段包含语句,所有分都送上
drop table #a
drop table #b
create table #a( dt1 datetime,dt2 datetime)
insert into #a select '2013-01-01','2013-01-31'
insert into #a select '2013-02-10','2013-02-20'
insert into #a select '2013-03-05','2013-03-31'
insert into #a select '2013-04-01','2013-04-30'


create table #b( dt1 datetime,dt2 datetime)
insert into #b select '2013-01-10','2013-01-15'
insert into #b select '2013-02-05','2013-02-10'
insert into #b select '2013-03-06','2013-03-20'



select * from #a
select * from #b

#b 中的日期 若 不包含在#a 中则返回 1,反之返回0

最后结果

2013-01-10 2013-01-15    1   
2013-02-052013-02-10    0  
2013-03-06      2013-03-20    1
[解决办法]

use tempdb
go

create table #a( dt1 datetime,dt2 datetime)
insert into #a select '2013-01-01','2013-01-31'
insert into #a select '2013-02-10','2013-02-20'
insert into #a select '2013-03-05','2013-03-31'
insert into #a select '2013-04-01','2013-04-30'


create table #b( dt1 datetime,dt2 datetime)
insert into #b select '2013-01-10','2013-01-15'
insert into #b select '2013-02-05','2013-02-10'
insert into #b select '2013-03-06','2013-03-20'

go

select 
b.*,Flag=case when a.dt1 is not null then 1 else 0 end
from #b as b
left join #a as a on a.dt1<=b.dt1 and a.dt2>=b.dt2

/*
dt1dt2Flag
2013-01-10 00:00:00.0002013-01-15 00:00:00.0001
2013-02-05 00:00:00.0002013-02-10 00:00:00.0000
2013-03-06 00:00:00.0002013-03-20 00:00:00.0001
*/

热点排行