在oracle中将一行拆分为多行

时间:2016-06-14 19:10:53

标签: sql oracle oracle11g

我有一个简单的选择查询,结果如下:

first_date | last_date  | outstanding
14/01/2015 | 14/04/2015 | 100000

我想把它拆分为

first_date | last_date  | period     | outstanding 
14/01/2015 | 31/01/2015 | 31/01/2015 | 100000 
01/02/2015 | 28/02/2015 | 28/02/2015 | 100000
01/03/2015 | 31/03/2015 | 31/03/2015 | 100000
01/04/2015 | 14/04/2015 | 31/04/2015 | 100000

如果不使用函数/过程,对象和光标,请告诉我如何操作。

1 个答案:

答案 0 :(得分:1)

尝试:

WITH my_query_result AS(
  SELECT date '2015-01-14' as first_date , date '2015-04-14' as last_date,
         10000 as outstanding
  FROM dual
)
SELECT  greatest( trunc( add_months( first_date, level - 1 ),'MM'), first_date ) 
           as first_date,
        least( trunc( add_months( first_date, level ),'MM')-1, last_date ) 
           as last_date,
        trunc( add_months( first_date, level ),'MM')-1 as period,
        outstanding
FROM my_query_result t
connect by level <= months_between( trunc(last_date,'MM'), trunc(first_date,'MM') ) + 1;

附注:4月只有30天,因此问题中的31/04/2015日期是错误的。