How can I generate a series of repeating numbers in PostgreSQL?

后端 未结 7 838
长发绾君心
长发绾君心 2021-01-17 07:36

In PostgreSQL, is it possible to generate a series of repeating numbers? For example, I want to generate the numbers 1 to 10, with each number repeated 3 times:



        
7条回答
  •  逝去的感伤
    2021-01-17 08:09

    For such small numbers CROSS JOIN two VALUES expressions:

    SELECT n
    FROM  (VALUES (1),(2),(3)) x(r)  -- repetitions (values are not used)
         ,(VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) y(n); -- numbers
    

    SQL Fiddle.

    This works for any sequence of numbers (including repeated or irregular patterns).
    For anything bigger and with regular sequential pattern use generate_series() as has been suggested.

提交回复
热议问题