Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

sql - Generating separate rows for each month in a date range

Basically I have one row of data, for example:

ID -   Start_Date -  End_Date

------------------------------------

XXA   1/23/14        3/12/14

And I want to create one row for each month between the Start_Date and End_Date, for each ID, for example:

ID -  Month -     Year

--------------------------

XXA  January      2014

XXA  February     2014

XXA  March         2014

Which is the best and most efficient way of doing this? I was thinking of using a cursor, but once this table is created, I need to join other ones to this one. I am new to oracle, and I am not sure if you can join other tables after you run a cursor and create a temporary table. Any help would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a simple row generation technique by using the CONNECT BY syntax:

with sample_data as 
  (select 'XXA' id, to_date('1/23/14','MM/DD/RR') start_date, to_date('3/12/14','MM/DD/RR') end_date from dual)
select id, to_char(add_months(start_date,level - 1),'Month YYYY') date_column
from sample_data
connect by level <= extract(month from end_date) - extract(month from start_date) + 1;

Edit Adding DISTINCT should allow this to work across rows, I believe, although I would be interested to be proven wrong. Edit 2 Modified example to handle multiple years (should have done that originally). (See example http://sqlfiddle.com/#!4/9eecb/4097/0.)

with sample_data as 
  ( select 'XXA' id, to_date('1/23/14','MM/DD/RR') start_date, to_date('3/12/15','MM/DD/RR') end_date from dual union all    
    select 'XXB' id, to_date('4/12/14','MM/DD/RR') start_date, to_date('6/18/15','MM/DD/RR') end_date from dual )
select distinct 
  id,
  to_char(add_months(start_date,level - 1),'Month YYYY') date_column,
  add_months(start_date,level -1) sortkey
from sample_data
connect by level <= ceil(months_between(trunc(end_date,'MM'), trunc(start_date,'MM'))) + 1
order by id, sortkey;

In my sandbox DB this yields:

ID  DATE_COLUMN     SORT_COL
XXA January   2014  23-JAN-2014 00:00:00
XXA February  2014  23-FEB-2014 00:00:00
XXA March     2014  23-MAR-2014 00:00:00
XXB April     2014  12-APR-2014 00:00:00
XXB May       2014  12-MAY-2014 00:00:00
XXB June      2014  12-JUN-2014 00:00:00

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...