日期:2014-05-17  浏览次数:20505 次

请问如何实现这样的查询?
最近在做一张报表,基础数据如下:
id tno time key
1001 螺丝 20130830 Y
1002 杯子 20130901 Y
1003 茶叶
1004 光盘
1005 绿茶 20130930 Y
1006 红茶 20131001 Y
查询“20130901”的数据,查询结果应为
id tno time key
1002 杯子 20130901 Y
1003 茶叶
1004 光盘
请问如何通过sql来实现

------解决方案--------------------
create table #tb(id int,tno varchar(10),[time] int,[key] varchar(1)) 
insert into #tb
select 1001,'螺丝',20130830,'Y'
union all select 1002,'杯子',20130901,'Y'
union all select 1003,'茶叶',null,null
union all select 1004,'光盘',null,null
union all select 1005,'绿茶',20130930,'Y'
union all select 1006,'红茶',20131001,'Y'

declare @d int
set @d=0
update #tb 
set [time]=case when [time] is not null then [time] else @d end
,@d=case when [time] is null then @d else [time] end

select id,tno,[time]=case when [key] is null then null else [time] end,[key]
from #tb
where [time]=20130901

/*
id tno time key
1002 杯子 20130901 Y
1003 茶叶 NULL NULL
1004 光盘 NULL NULL
*/