在Postgres中将列和值拆分为多行

时间:2016-01-13 17:41:06

标签: sql postgresql split

假设我有一个这样的表:

        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

有一种简单的方法吗?

1 个答案:

答案 0 :(得分: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)