2016-01-13 31 views
0

多行假設我有一個像這樣的表:拆分列和值入Postgres的

 subject  | flag | first_date | last_date 
    ----------------+---------------------------------- 
    this is a test | 2 | 1/1/2016 | 1/4/2016 

弄成這個樣子:

 subject  | flag | date 
    ----------------+------------------ 
    this is a test | .5 | 1/1/2016 
    this is a test | .5 | 1/2/2016 
    this is a test | .5 | 1/3/2016 
    this is a test | .5 | 1/4/2016 

是否有一個簡單的方法來做到這一點?

+0

通常我會傾向於做這樣的事情在一個腳本語言。可能有辦法在SQL中破解它,但可能不會很漂亮。有什麼理由需要在SQL中完成? – njachowski

+1

腳本技能薄弱 –

回答

1

您可以使用generate_series()first_datelast_date之間產生連續的天數列表:

with dates as (
    select d::date, last_date- first_date+ 1 ct 
    from test, generate_series(first_date, last_date, '1d'::interval) d 
    ) 
select subject, flag/ ct flag, d date 
from dates 
cross join test; 

    subject  |   flag   | date  
----------------+------------------------+------------ 
this is a test | 0.50000000000000000000 | 2016-01-01 
this is a test | 0.50000000000000000000 | 2016-01-02 
this is a test | 0.50000000000000000000 | 2016-01-03 
this is a test | 0.50000000000000000000 | 2016-01-04 
(4 rows)