2011-03-08 42 views
0

请使用以下示例数据。在不使用临时表的情况下在结果集中包含数据不符合过滤条件

declare @tbl table (id int, fid int, arrival datetime, created datetime) 
insert into @tbl select 1, 10, DATEADD(dd, -10, GETDATE()), DATEADD(dd, -6, getdate()) 
insert into @tbl select 1, 10, DATEADD(dd, -10, GETDATE()), DATEADD(dd, -6, getdate()) 
insert into @tbl select 1, 10, DATEADD(dd, -10, GETDATE()), null 
insert into @tbl select 2, 20, DATEADD(dd, -3, GETDATE()), DATEADD(dd, -2, getdate()) 
insert into @tbl select 2, 20, DATEADD(dd, -3, GETDATE()), null 

我想都行between arrival '2011-02-25' and '2011-02-28'此日期'2011-02-20'包括创建日期为空之后创建的。

查询1:

select * from @tbl 
where arrival >= '2011-02-25' and arrival < '2011-02-28' 
and created >= '2011-02-20' 

上面的查询取两行,但我需要FID = 10,创造了迄今为止空

Qery2的第三行:FID = 20的选择行,我不要”因为它不在到达日期的范围内,因此需要。

select * from @tbl 
where arrival >= '2011-02-25' and arrival < '2011-02-28' 
and created >= '2011-02-20' OR created is null 

这是样本数据。原始查询从不同表中提取数据,并且已与10个表连接,因此我不想再次运行查询以将行包含在临时表中。

谢谢。

编辑: 对不起,想问这个,但提出了错误的问题。谢谢你的帮助。

declare @tbl table (id int, fid int, arrival datetime, created datetime) 
insert into @tbl select 1, 10, DATEADD(dd, -10, GETDATE()), DATEADD(dd, -6, getdate()) 
insert into @tbl select 1, 10, DATEADD(dd, -10, GETDATE()), DATEADD(dd, -6, getdate()) 
insert into @tbl select 1, 10, null, DATEADD(dd, -6, getdate()) 
insert into @tbl select 2, 20, DATEADD(dd, -3, GETDATE()), DATEADD(dd, -2, getdate()) 
insert into @tbl select 2, 20, null, DATEADD(dd, -2, getdate()) 

select * from @tbl 
where arrival >= '2011-02-26' and arrival < '2011-02-28' 

需要的FID = 10第三排过其中arrival日期是NULL

回答

3

这可能会做你想要什么。

;with cte as 
(
    select distinct fid 
    from @tbl 
    where 
    arrival >= '2011-02-26' and 
    arrival < '2011-02-28' 
) 
select * 
from cte as C 
    inner join @tbl as T 
    on C.fid = T.fid 
where 
    (arrival >= '2011-02-26' and 
    arrival < '2011-02-28') or 
    arrival is null 
+0

张贴...和ISNULL(创建, '2011-02-20')> = '2011-02-20' – Arvo 2011-03-08 10:59:16

+0

@Mikael谢谢。请参阅我的编辑。再次感谢您的答复。 – Kashif 2011-03-08 11:14:59

+0

@Muhammad更新回答 – 2011-03-08 11:39:36

1

我觉得应该工作:

select * from @tbl 
where (arrival >= '2011-02-25' and arrival < '2011-02-28') 
and (created >= '2011-02-20' or created is Null) 

根据你的编辑你需要这样做:

select * from @tbl 
where ((arrival >= '2011-02-25' and arrival < '2011-02-28') or arrival is null) 
and (created >= '2011-02-20' or created is Null) 

这将返回3 FID = 10行,但是它会也返回行ID = 2和FID = 20,因为该行也满足过滤条件。

+0

Thanks @Barry,请参阅我的编辑。谢谢你的帮助。 – Kashif 2011-03-08 11:16:03

+0

@穆罕默德 - 更新我的回答 – codingbadger 2011-03-08 11:21:19

+0

感谢您再次回答。那就是问题所在。我已经在我的真实数据中尝试了这一点。在这个字段中,我有1000个行在实际数据中有NULL,并且这将返回全部。任何其他解决方案或我必须使用临时表或CTE来获得所需的结果集。 – Kashif 2011-03-08 11:24:21

0

这是一个稍微不同的看法从较明显的答案上述

select * from @tbl where arrival >= '2011-02-25' and arrival < '2011-02-28' and COALESCE(created,'2011-02-25') >= '2011-02-20'

+0

感谢@Raam,请参阅我的编辑和@ Barry的回答。 – Kashif 2011-03-08 11:25:29

相关问题