请使用以下示例数据。
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'
包括创建的日期null。
查询1:
select * from @tbl
where arrival >= '2011-02-25' and arrival < '2011-02-28'
and created >= '2011-02-20'
上面的查询获取两行,但我需要第三行FID = 10,它创建了日期null
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'
在arrival
日期为NULL
答案 0 :(得分: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
答案 1 :(得分: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,因为该行也满足过滤条件。
答案 2 :(得分:0)
这与上面发布的更明显的答案略有不同
select * from @tbl
where arrival >= '2011-02-25' and arrival < '2011-02-28'
and COALESCE(created,'2011-02-25') >= '2011-02-20'