繁体   English   中英

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

[英]Split column and values into multiple rows in 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

是否有捷径可寻?

您可以使用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)    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM