读书人

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

发布时间: 2012-03-08 13:30:13 作者: rapoo

昨夜小楼??再求 一个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
*/

读书人网 >SQL Server

热点推荐