2011-02-26 73 views
0

使用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

  • 如果開始和結束日期,請在休假表中特定的ID,那麼就應該顯示爲「離開」事件表的特定日期

查詢

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

  • 如果是可用的開始日期和結束日期不詳的假表爲具體的ID,那麼就應該顯示爲「離開」事件表其餘日期

查詢

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 
…. 

上面的查詢工作,但我要製作成單個查詢與這兩個條件

如何查詢上述條件。

需要查詢幫助

回答

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)) 
+0

@ Verrig0 - 超時過期顯示當我運行查詢。 – Gopal 2011-02-26 11:07:07

0

試試這個。如果將來爲離開表使用虛擬結束日期,它基本上是相同的查詢。

我選擇了2079年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') 
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