Printing series in postgres

Viewed 59

I am a beginner in Postgres and I want to print series, say, a table contains 1 column as id with rows with data 1,2,3.

      id
---------------
      1
      2
      3

The output should be like, the value in the first row * number of times it prints.

3 Answers

One option, just using a self join without any auxiliary tables or sequences:

SELECT t1.id
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.id >= t2.id
ORDER BY
    t1.id;

Demo

You can use a recursive cte:

with cte(v, c) as (
   select id, id from test_table
   union all
   select v, c - 1 from cte where c > 1
)
select v from cte order by v;

You can use generate_series()

select t.id
from the_table
  cross join generate_series(1, t.id);
order by t.id;
Related