2013-07-18 45 views
0

我有一個包含員工缺席條目的表。該行包含員工編號,沒有和很多更像缺少數據類型,批准的第一天和最後一天,等如何擺動兩個日期列並填寫多個重疊日期的空白

absencecalendarline: 

EMPLOYEENUMBER | FIRSTDAYOFABSENCE | LASTDAYOFABSENCE | ABSENCETYPE | APPROVED 
---------------+-------------------+------------------+-------------+---------- 
1    | 2013-01-01  | 2013-01-04  | VACATION | TRUE 
2    | 2013-01-01  | 2013-01-02  | VACATION | TRUE 
3    | 2013-02-05  | 2013-02-08  | VACATION | TRUE 
2    | 2013-02-06  | 2013-02-07  | VACATION | TRUE 

我想創建一個與所有列出的條目沒有一個視圖日期。像這樣的東西。

desired result: 

EMPLOYEENUMBER | ABSENCEDATE | ABSENCETYPE | APPROVED 
---------------+-------------+-------------+---------- 
1    | 2013-01-01 | VACATION | TRUE 
1    | 2013-01-02 | VACATION | TRUE 
1    | 2013-01-03 | VACATION | TRUE 
1    | 2013-01-04 | VACATION | TRUE 
2    | 2013-01-01 | VACATION | TRUE 
2    | 2013-01-02 | VACATION | TRUE 
3    | 2013-02-05 | VACATION | TRUE 
..    ..   ..   .. 
3    | 2013-02-08 | VACATION | TRUE 
2    | 2013-02-06 | VACATION | TRUE 
2    | 2013-02-07 | VACATION | TRUE 

我也有一個日期表,CALENDARDAY裝載日曆和相關信息,如週數,月數等所有日期幫我帶日期的人口。

我在這個查詢嘗試導致下面的代碼:

SELECT unpvt.EMPLOYEENUMBER, unpvt.FIRSTORLAST, unpvt.ABSENCEDATE, unpvt.FIRSTABSENCE, 
unpvt.LASTABSENCE, unpvt.ABSENCETYPE, unpvt.APPROVED, cd.THEDATE, cd.WEEKNUMBER, 
    (SELECT TOP 1 EMPLOYEENUMBER 
    FROM dbo.ABSENCECALENDARLINE asq 
    WHERE cd.THEDATE BETWEEN asq.FIRSTDAYOFABSENCE AND asq.LASTDAYOFABSENCE 
    ORDER BY cd.THEDATE DESC) EMPLOYEENUMBER 
FROM 
    (SELECT EMPLOYEENUMBER, FIRSTDAYOFABSENCE, LASTDAYOFABSENCE, FIRSTDAYOFABSENCE AS 
    FIRSTABSENCE, LASTDAYOFABSENCE AS LASTABSENCE, ABSENCETYPE, APPROVED 
    FROM dbo.ABSENCECALENDARLINE acl) a 
UNPIVOT 
    (ABSENCEDATE FOR FIRSTORLAST IN 
     (FIRSTDAYOFABSENCE, LASTDAYOFABSENCE) 
    ) AS unpvt 
RIGHT JOIN dbo.CALENDARDAY cd ON unpvt.ABSENCEDATE = cd.THEDATE 
WHERE CAST(THEDATE AS datetime) BETWEEN '2013-01-01' AND '2013-12-31' 
ORDER BY THEDATE 

我這個迎接挑戰是SELECT子查詢,需要一個TOP 1造成重疊缺席只返回沒有一位員工的上給定日期。此列上的COUNT返回當天缺席的人數。

我是不是覺得太複雜了?我怎樣才能輕鬆實現我想要的結果?任何幫助將不勝感激。

最好的問候, 亞歷山大

回答

0

除非我失去了一些東西,我覺得你在這個複雜:

SELECT a.EMPLOYEENUMBER, b.DATE, a.ABSENCETYPE, a.APPROVED 
FROM Table1 a 
JOIN Calendar b 
    ON b.Date BETWEEN a.FIRSTDAYOFABSENCE AND a.LASTDAYOFABSENCE 

演示:SQL Fiddle

+0

你是100%正確。我正在想辦法變得複雜。我想這是一個「樞紐」機會,只是把我的注意力集中在一起,使得它更難以解決!非常感謝您讓我的雙腳重新站立在地面上。 – Alexander

+0

我確實有時會這樣做,注意一種技術,並嘗試將它塞進它沒有業務的地方。 –