SQL, Auxiliary table of numbers

前端 未结 7 2014
自闭症患者
自闭症患者 2020-11-21 22:24

For certain types of sql queries, an auxiliary table of numbers can be very useful. It may be created as a table with as many rows as you need for a particular task or as a

7条回答
  •  北海茫月
    2020-11-21 23:18

    edit: see Conrad's comment below.

    Jeff Moden's answer is great ... but I find on Postgres that the Itzik method fails unless you remove the E32 row.

    Slightly faster on postgres (40ms vs 100ms) is another method I found on here adapted for postgres:

    WITH 
        E00 (N) AS ( 
            SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
            SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 ),
        E01 (N) AS (SELECT a.N FROM E00 a CROSS JOIN E00 b),
        E02 (N) AS (SELECT a.N FROM E01 a CROSS JOIN E01 b ),
        E03 (N) AS (SELECT a.N FROM E02 a CROSS JOIN E02 b 
            LIMIT 11000  -- end record  11,000 good for 30 yrs dates
        ), -- max is 100,000,000, starts slowing e.g. 1 million 1.5 secs, 2 mil 2.5 secs, 3 mill 4 secs
        Tally (N) as (SELECT row_number() OVER (ORDER BY a.N) FROM E03 a)
    
    SELECT N
    FROM Tally
    

    As I am moving from SQL Server to Postgres world, may have missed a better way to do tally tables on that platform ... INTEGER()? SEQUENCE()?

提交回复
热议问题