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

4xrmg8kj  于 2023-05-28  发布在  PostgreSQL
关注(0)|答案(1)|浏览(96)

假设我有一张这样的table:
| 主题|旗|第一日期|最后日期|
| - -----|- -----|- -----|- -----|
| 这是个测试|2| 2016年1月1日|2016年1月4日|
变成这样:
| 主题|旗|日期|
| - -----|- -----|- -----|
| 这是个测试|0.5| 2016年1月1日|
| 这是个测试|0.5| 2016年1月2日|
| 这是个测试|0.5| 2016年1月3日|
| 这是个测试|0.5| 2016年1月4日|
有什么简单的方法吗?

u5i3ibmn

u5i3ibmn1#

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

相关问题