2013-04-21 63 views
-2

我有一個名爲holiday_master的表,其中3列是從那裏命名from_date,to_date和duration.Now當用戶輸入日期範圍時,讓daterange1和daterange2爲基礎的假期表,寫一個sql來查找節假日的數量。它將包括from_date和to_date。在sql中給定日期範圍內找到假期的數量

對於例如 FROM_DATE TO_DATE持續時間 2012/08/01 2012/08/03 3 2012年9月17日2012年9月24日8

用戶輸入:2012年7月30日至2012/08/02(節假日數:2) 2012年9月20日2012年9月29日到(節假日數:5)

+0

您想如何處理重疊假期? – HABO 2013-04-23 17:30:42

回答

1

下面的查詢應該工作:

select coalesce(sum(datediff(day, 
        (case when h.from_date < t.fromdate then t.fromdate else h.from_date end), 
        (case when t.to_date > t.todate then t.todate else h.to_date end) 
        ), 0) 
from (select @daterange1 as fromdate, @daterange2 as todate) const left outer join 
    holidays h 
    on h.from_date <= todate and h.to_date >= from_date; 

這裏是邏輯。首先,爲了方便起見,我只是將常量放到一個常量表中(限制了「@」鍵的壓力)。然後,查詢離開加入假期表 - 必要的情況下,在該期間沒有假期。

然後它執行比較重疊時間段的邏輯。如果假期的開始時間在時間​​段之前,則開始時間段的開始。最後同樣的事情。然後,將所有這些時間段加起來。

根據處理「to_date」的方式,您可能需要在期間中添加「1」。是否包含「to_date」作爲假期。如果包含爲假期,則邏輯如下:

select coalesce(sum(1+datediff(day, 
        (case when h.from_date < t.fromdate then t.fromdate else h.from_date end), 
        (case when t.to_date > t.todate then t.todate else h.to_date end) 
        ), 0)