Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate (repeat) rows in sql query result

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.

like image 674
icl7126 Avatar asked Jul 18 '26 05:07

icl7126


1 Answers

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);
like image 76
Gordon Linoff Avatar answered Jul 20 '26 19:07

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!