我的表格如下:
PersonnelId
AbsenceReason
AbsenceFrom
AbsenceTo
现在我想要一个返回以下结果的查询。 我提供了一个日期范围,并且无论该人是否缺席,都应该返回所有日期。 例如:
PersonnelId = 4
AbsenceReason = Holiday
AbsenceFrom = 2/12/2012
AbsenceTo = 10/12/2012
当我运行查询时,我将12月作为输入。 我希望结果显示以下内容:
1/12/2012 "Available"
2/12/2012 "Holiday"
3/12/2012 "Holiday"
...
11/12/2012 "Available"
...
答案 0 :(得分:1)
类似的东西:
SQL> create table person (PersonnelId primary key, AbsenceReason , AbsenceFrom , AbsenceTo)
2 as
3 select 4, 'Holiday', '2/12/2012', '10/12/2012'
4 from dual;
Table created.
只需将to_date('12-2012', 'mm-yyyy')
设置为适用的月/年:
SQL> with mon as (select d
2 from (select to_date('12-2012', 'mm-yyyy') + rownum - 1 d
3 from dual
4 connect by level <= 31)
5 where trunc(d, 'mm') = to_date('12-2012', 'mm-yyyy'))
6 select personnelId, m.d,
7 case
8 when m.d between p.AbsenceFrom and p.AbsenceTo then 'Holiday'
9 else 'Available'
10 end absent
11 from mon m
12 cross join person p
13 order by 1, 2;
PERSONNELID D ABSENT
----------- ---------- ---------
4 01/12/2012 Available
4 02/12/2012 Holiday
4 03/12/2012 Holiday
4 04/12/2012 Holiday
4 05/12/2012 Holiday
4 06/12/2012 Holiday
4 07/12/2012 Holiday
4 08/12/2012 Holiday
4 09/12/2012 Holiday
4 10/12/2012 Holiday
4 11/12/2012 Available
4 12/12/2012 Available
4 13/12/2012 Available
4 14/12/2012 Available
4 15/12/2012 Available
4 16/12/2012 Available
4 17/12/2012 Available
4 18/12/2012 Available
4 19/12/2012 Available
4 20/12/2012 Available
4 21/12/2012 Available
4 22/12/2012 Available
4 23/12/2012 Available
4 24/12/2012 Available
4 25/12/2012 Available
4 26/12/2012 Available
4 27/12/2012 Available
4 28/12/2012 Available
4 29/12/2012 Available
4 30/12/2012 Available
4 31/12/2012 Available
答案 1 :(得分:0)
这对你有帮助吗?请尝试:
SELECT date_col, NVL(AbsenceReason, 'Available') AS Reason
FROM (SELECT To_date('01-JUN-2012', 'dd-mon-yyyy')
+ LEVEL - 1 AS date_col
FROM dual
CONNECT BY LEVEL <= To_date('06-JUL-2012', 'dd-mon-yyyy') -
To_date('01-JUN-2012', 'dd-mon-yyyy') +
1)d
left join yourtable t1
ON d.date_col BETWEEN t1.absencefrom AND t1.absenceto;
在此示例中,'01-JUN-2012'
来自日期,'06-JUL-2012'
是迄今为止。