I'm dealing with a table of user subscriptions info, where each row is a specific user along with the start date of their subscription and how many months they have pre-paid. I'm trying to break this table out so that there's one row per month. I'm on Redshift, and the only other answers I've found suggest the generate_series
which doesn't always work on Redshift.
Starting data:
userid | amount_paid | start_date | months
------------------------------------------------
asdf | 20.00 | 2020-01-01 | 1
------------------------------------------------
qwer | 10.00 | 2021-06-01 | 3
Desired results (months
column value doesn't matter but I'd like amount_paid
to be 0 or null for new rows):
userid | amount_paid | start_date | months
------------------------------------------------
asdf | 20.00 | 2020-01-01 | 1
------------------------------------------------
qwer | 10.00 | 2021-06-01 | 3
------------------------------------------------
qwer | 0 | 2021-07-01 | 3
------------------------------------------------
qwer | 0 | 2021-08-01 | 3
generate_series()
is a Leader-only function, which means that it can't be used in a query that references any tables. You could obtain similar behaviour by joining to a table that has a series of dates, or even just a series of numbers. – Hesperianstart_date + interval '1 month' * number_from_cte
. It would effectively generate one row for each joined value, and you would use aWHERE
to limit the number of rows joined. – Hesperian