3

Let's say I have a table with two rows

 id | value |
----+-------+
 1  |   2   |
 2  |   3   |

I want to write a query that will duplicate (repeat) each row based on the value.
I want this result (5 rows total):

 id | value |
----+-------+
 1  |   2   |
 1  |   2   |
 2  |   3   |
 2  |   3   |
 2  |   3   |

I'm using PostgreSQL 9.4.

1 Answer 1

12

You can use generate_series():

select t.id, t.value
from (select t.id, t.value, generate_series(1, t.value)
      from t 
     ) t;

You can do the same thing with a lateral join:

select t.id, t.value
from t, lateral
     generate_series(1, t.value);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.