Search code examples
sqlpostgresqlgenerate-seriesset-returning-functions

Repeat row number of times based on column value


I have table which looks like this:

| name |  start_date   |  duration_day|
========================================
|   A  |  2015-01-01   |       3      |
|   B  |  2015-01-02   |       2      |

And now I want to get an output like so:

   | name |     date   |
   =====================
   |  A   | 2015-01-01 |
   |  A   | 2015-01-02 |
   |  A   | 2015-01-03 |
   |  B   | 2015-01-02 |
   |  B   | 2015-01-03 |

How can I do this in PostgreSQL?


Solution

  • Borrowing from Abelisto's answer, you can generate a series from the duration_day value with the generate_series() table function in the row source list. The function uses the duration_day value from my_table through an implicit lateral join.

    SELECT name, start_date + n AS date
    FROM my_table, generate_series(0, duration_day - 1) AS x(n);