I have this data in my postgresSQL db.
id | client_id | num |
---|---|---|
1 | 1 | 3 |
2 | 2 | 1 |
3 | 3 | 2 |
I want to create multiple entries for each unique client corresponding to the number in the num column. For example to complete this task for the above column I would have.
id | client_id | num |
---|---|---|
1 | 1 | 3 |
2 | 2 | 1 |
3 | 3 | 2 |
4 | 1 | 1 |
5 | 1 | 2 |
6 | 3 | 1 |
Filling in all numbers between 0 and num with new entries. I’d prefer to do this in a single command or loop versus the manually adding entries method that I know. Any help would be appreciated, thanks.
2
Answers
You can do it with a
RECURSIVE
query, that decrements yournum
index by one at each iteration, and stop when this value is equal to 1.Check the demo here.
You can do this by joining with
generate_series
usingnum
as the max value. Userow_number
to generate an ID for each row.Demonstration