Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSTGRES generate n rows based on a value n

Tags:

sql

postgresql

I need to generate a view, in postgres, containing n rows based on a value n in a column.

Let's make an example. I have a table like this:

   A*  |  B   |  C
 --------------------
  abc  |  def |  4
  ghi  |  jkl |  7

I need to generate a view made like this:

   A  |  B   |  C
------------------------
  abc  |  def |  4
  abc  |  def |  4
  abc  |  def |  4
  abc  |  def |  4
  ghi  |  jkl |  7
  ghi  |  jkl |  7
  ghi  |  jkl |  7
  ghi  |  jkl |  7
  ghi  |  jkl |  7
  ghi  |  jkl |  7
  ghi  |  jkl |  7

Is there a way to do it smartly? At the moment I am doing N UNION ALL with N big enough to cover all the cases (e.g. in this case 7).

like image 374
balsick Avatar asked Dec 14 '25 01:12

balsick


2 Answers

Just use generate_series():

select t.*, generate_series(1, t.c)
from t ;

If you don't want the value in the result set, use a lateral join:

select t.*
from t, lateral
     generate_series(1, t.c);

Or:

select t.*
from t cross join lateral
     generate_series(1, t.c);
like image 120
Gordon Linoff Avatar answered Dec 16 '25 20:12

Gordon Linoff


Using Recursive CTE

You can try this.

WITH RECURSIVE result(A,B,L,C) AS(
    SELECT A,B,1 L,MAX(C) C
   FROM T
    GROUP BY A,B
    UNION ALL
    SELECT A,B,L+1,C
    FROM result
    WHERE L+1 <= C
)
SELECT A,B,C
FROM result
ORDER BY C,A

SQLFIDDLE

like image 24
D-Shih Avatar answered Dec 16 '25 19:12

D-Shih



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!