如何在Oracle

时间:2018-04-08 07:04:33

标签: sql oracle

如何创建日历表Oracle。就像我有假期表

Id  FromDate    ToDate  Description
1   1-Feb-11    3-Feb-11    Maintance
3   2-Sep-09    5-Sep-09    Eid Holiday Fine Block
4   3-Dec-09    4-Dec-09    Due to System Problem
5   4-Dec-07    04-Dec-07   National Day

我想从最小CTE和最大fromdate的此表格中todate。{/ p>

期待表格。

Date        HolidayName

11-Feb-11   Maintance
12-Feb-11   Maintance
13-Feb-11   Maintance
02-Sep-09   Eid Holiday
03-Sep-09   Eid Holiday
04-Sep-09   Eid Holiday
05-Sep-09   Eid Holiday

2 个答案:

答案 0 :(得分:2)

可以使用

select FromDate+level-1 "Date", Description "HolidayName" from holiday connect by level <= ToDate - FromDate + 1 group by FromDate+level-1, Description order by 1; 子句:

{{1}}

demo

答案 1 :(得分:1)

IN oracle 11g 2你可以使用CTE Recursive

像这样。

WITH CTE(from_date, i, datediff,description) AS
(
  SELECT from_date, 1 AS i, trunc(to_date - from_date) as datediff,description
  FROM t
  UNION ALL
  SELECT from_date, i + 1, datediff,description
  FROM CTE
  WHERE i <= datediff
)
, dates as (select i, from_date + i - 1 as "Date",description from CTE)
SELECT "Date",description "HolidayName"
FROM dates
ORDER BY description desc

Sqlfiddle:http://sqlfiddle.com/#!4/ac34c/7