简体   繁体   中英

Postgresql split single row into multiple rows based on date

In my case, we have a table ABC with the supposed 1 row.

id name start_date end_date
1 Rahul 01/01/2021 06/01/2021

but while retrieving I would like to get multiple rows where the start date is incrementing by 1 like till it's less than or equal to the end date.

id name start_date end_date
1 Rahul 01/01/2021 06/01/2021
1 Rahul 02/01/2021 06/01/2021
1 Rahul 03/01/2021 06/01/2021
1 Rahul 04/01/2021 06/01/2021
1 Rahul 05/01/2021 06/01/2021
1 Rahul 06/01/2021 06/01/2021

Please let me know how we can do that.

Use generate_series() . Assuming the data is by day:

select t.id, t.name, gs.date, t.end_date
from t cross join lateral
     generate_series(start_date, end_date, interval '1 day') gs(date);

If your data is actually by month, you would just change '1 day' to '1 month' .

Note: Postgres allows set returning functions in the select , so you could write this as:

select t.id, t.name,
       generate_series(start_date, end_date, interval '1 day') as date,
       t.end_date
from t;

However, I don't think that is a good practice. I am uncomfortable with select expressions changing the number of rows being returned by a query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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