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

昨夜小楼?再求 一个SQL语句解决方案

2012-03-08 
昨夜小楼??再求 一个SQL语句当输入一个日期时,想查出输入日期落在哪个適用開始日-適用終了日之间,并且将其

昨夜小楼??再求 一个SQL语句
当输入一个日期时,想查出输入日期落在哪个   適用開始日-適用終了日   之间,
并且将其之前或之后的   適用開始日-適用終了日   也查出来。如果输入日期没有落在任何適用開始日-適用終了日   之间,就将其之前或之后的   適用開始日-適用終了日   也查出来。

预想结果:   输入日期为:   20040101
職員番号   適用開始日   適用終了日   過去開始日     過去終了日   未来開始日   未来終了日
100          20010101       20050101       19960101         20000101       20050101       20100101
200                                                                                                       20050101       20100101
300                                                         19900101         19950101
400             19960101       20000101                                                     20050101       20100101


表1
職員番号,適用開始日   是主键

職員番号  適用開始日  適用終了日
100          19900101       19950101
100          19960101       20000101
100          20010101       20050101
100          20050101       20100101
100          20100101       20150101
200          20050101       20100101
200          20100101       20150101
300          19900101       19950101
400          19900101       19950101
400          19960101       20000101
400          20050101       20100101
400          20100101       20150101

不知道能不能查出这样的结果,谢谢!


[解决办法]
如果输入日期没有落在任何適用開始日-適用終了日 之间,就将其之前或之后的 適用開始日-適用終了日 也查出来。

是之前和之后都要,还是只要一个.你的结果没看明白.
[解决办法]
--原始数据:@1
declare @1 table(EmpID int,Start bigint,Stop bigint)
insert @1
select 100, '19900101 ', '19950101 ' union all
select 100, '19960101 ', '20000101 ' union all
select 100, '20010101 ', '20050101 ' union all
select 100, '20050101 ', '20100101 ' union all
select 100, '20100101 ', '20150101 ' union all
select 200, '20050101 ', '20100101 ' union all
select 200, '20100101 ', '20150101 ' union all
select 300, '19900101 ', '19950101 ' union all
select 400, '19900101 ', '19950101 ' union all
select 400, '19960101 ', '20000101 ' union all
select 400, '20050101 ', '20100101 ' union all
select 400, '20100101 ', '20150101 '

/*
EmpID -> 職員番号
Start -> 適用開始日
Stop -> 適用終了日
*/

declare @Date bigint
set @Date = 20040101

select
職員番号=a.EmpID,
適用開始日=b.Start,


適用終了日=b.Stop,
過去開始日=c.Start,
過去終了日=c.Stop,
未来開始日=d.Start,
未来終了日=d.Stop
from
(select EmpID from @1 group by EmpID) a
left join
(select * from @1 where @Date> =Start and @Date <Stop) b
on a.EmpID=b.EmpID
left join
(select * from @1 a where Start=(select max(Start) from @1 where EmpID=a.EmpID and Stop <@Date)) c
on a.EmpID=c.EmpID
left join
(select * from @1 a where Start=(select min(Start) from @1 where EmpID=a.EmpID and Start> =@Date)) d
on a.EmpID=d.EmpID

/*
職員番号 適用開始日 適用終了日 過去開始日 過去終了日 未来開始日 未来終了日
100 20010101 20050101 19960101 20000101 20050101 20100101
200 NULL NULL NULL NULL 20050101 20100101
300 NULL NULL 19900101 19950101 NULL NULL
400 NULL NULL 19960101 20000101 20050101 20100101
*/

热点排行