使用SQL Server 2005
离开表
ID StartDate EndDate
001 02/03/2010 02/03/2010
002 02/03/2010 null
…
活动表
ID Date
001 02/03/2010
001 02/04/2010
001 02/05/2010
002 02/03/2010
002 02/04/2010
002 02/05/2010
….
所有日期列数据类型均为datetime
。
我有n个id。
我想创建一个状态列,将事件表中的日期与离开表中的结束日期进行比较。
条件1
查询
Select
id, date
, CASE WHEN t2.id IS NULL THEN null ELSE ‘Leave’ END AS status
from event table as t1
left outer join leave table as t2 on
t1.id = t2.id and t1.date between t2.startdate and t2.enddate
条件2
查询
Select
id, date,
, CASE WHEN t2.id IS NULL THEN null ELSE ‘Leave’ END AS status
from event table as t1
left outer join leave table as t2 on
t1.id = t2.id and t1.date > t2.startdate
预期产出
ID Date Status
001 02/03/2010 Leave
001 02/04/2010
001 02/05/2010
002 02/03/2010 Leave
002 02/04/2010 Leave
002 02/05/2010 Leave
….
以上查询正在运行,但我想使用两个条件进行单个查询
如何查询上述情况。
需要查询帮助
答案 0 :(得分:1)
也许这对你有用:
Select
id, date
, CASE WHEN t2.id IS NULL THEN null ELSE ‘Leave’ END AS status
from event table as t1
left outer join leave table as t2 on
t1.id = t2.id
where (t1.date between t2.startdate and t2.enddate)
or (t2.enddate is null and (t1.date > t2.startdate))
答案 1 :(得分:0)
试试这个。如果您将来使用假结束日期,则它基本上是相同的查询。
我选择06年6月6日作为最高的smalldatetime值,但您可以根据需要更改
Select
id, date
, CASE WHEN t2.id IS NULL THEN null ELSE ‘Leave’ END AS status
from
eventtable as t1
left outer join
leave table as t2 on t1.id = t2.id and
t1.date between t2.startdate and ISNULL(t2.enddate, '20790606')
答案 2 :(得分:0)
我认为在日期中使用'或'条件会成为性能问题(索引使用等)。
也许工会(或工会全部)会更好地运作:
Select
id, date
, CASE WHEN t2.id IS NULL THEN null ELSE ‘Leave’ END AS status
from event table as t1
left outer join leave table as t2 on
t1.id = t2.id and t1.date between t2.startdate and t2.enddate
Union
Select
id, date,
, CASE WHEN t2.id IS NULL THEN null ELSE ‘Leave’ END AS status
from event table as t1
left outer join leave table as t2 on
t1.id = t2.id and t1.date > t2.startdate