oracle sql总计连续范围的天数

时间:2015-01-20 13:03:02

标签: oracle oracle-sqldeveloper

我有一张包含日期范围的表格,我只计算连续日期范围的天数...

-----------------------------------
| table RANGES                    |
----------------------------------
| d_start    | d_end       | days |
| (date)     | (date)      | (num)|
-----------------------------------
| 2014-02-01 | 2014-02-05  |   4  |
| 2014-02-06 | 2014-02-11  |   5  |
| 2014-03-22 | 2014-03-25  |   3  |
| 2014-04-02 | 2014-04-10  |   8  |
| 2014-04-11 | 2014-04-20  |   9  |
-----------------------------------

我需要在日期范围不是连续性的情况下累计休息日,结果如下:

| 2014-02-01 | 2014-02-11  |   9  |
| 2014-03-22 | 2014-03-25  |   3  |
| 2014-04-02 | 2014-04-20  |  17  |

我尝试用LEAD来检查下一条记录的d_start是否等于d_end但是我无法达到目标。

非常感谢任何想法! 马可

1 个答案:

答案 0 :(得分:0)

答案非常棘手:

SQL> create table tmp$dates (d_start date, d_end date);

Table created

SQL> insert into tmp$dates values (DATE '2014-02-01', DATE '2014-02-05');

1 row inserted

SQL> insert into tmp$dates values (DATE '2014-02-06', DATE '2014-02-11');

1 row inserted

SQL> insert into tmp$dates values (DATE '2014-03-22', DATE '2014-03-25');

1 row inserted

SQL> insert into tmp$dates values (DATE '2014-04-02', DATE '2014-04-10');

1 row inserted

SQL> insert into tmp$dates values (DATE '2014-04-11', DATE '2014-04-20');

1 row inserted

SQL> select min(d_start), max(d_end), max(d_end) - min(d_start) + 1 n#
  2  from tmp$dates d
  3  start with d_start not in (select d_end + 1 from tmp$dates)
  4  connect by prior d_end = d_start - 1
  5  group by level - rownum
  6  order by 1;

MIN(D_START) MAX(D_END)          N#
------------ ----------- ----------
01.02.2014   11.02.2014          11
22.03.2014   25.03.2014           4
02.04.2014   20.04.2014          19