我有一张员工缺勤表格。这些行包含员工编号,缺席的第一天和最后一天以及更多数据,如缺勤类型,已批准等等。
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 :(得分: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