Duplicate (repeat) rows in sql query result

删除回忆录丶 提交于 2019-12-08 00:47:59

问题


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:


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);


来源:https://stackoverflow.com/questions/35293084/duplicate-repeat-rows-in-sql-query-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!