Insert multiple rows in one table based on number in another table

前端 未结 1 1286
抹茶落季
抹茶落季 2020-12-11 06:05

I am creating a database for the first time using Postgres 9.3 on MacOSX.

Let\'s say I have table A and B. A starts off as emp

相关标签:
1条回答
  • 2020-12-11 07:09

    Answer to original question

    Postgres allows set-returning functions (SRF) to multiply rows. generate_series() is your friend:

    INSERT INTO b (all_names, birthday)
    SELECT names, current_date -- AS birthday ??
    FROM  (SELECT names, generate_series(1, number) FROM a);
    

    Since the introduction of LATERAL in Postgres 9.3 you can do stick to standard SQL: the SRF moves from the SELECT to the FROM list:

    INSERT INTO b (all_names, birthday)
    SELECT a.names, current_date -- AS birthday ??
    FROM   a, generate_series(1, a.number) AS rn
    

    LATERAL is implicit here, as explained in the manual:

    LATERAL can also precede a function-call FROM item, but in this case it is a noise word, because the function expression can refer to earlier FROM items in any case.

    Reverse operation

    The above is the reverse operation (approximately) of a simple aggregate count():

    INSERT INTO a (name, number)
    SELECT all_names, count(*)
    FROM   b
    GROUP  BY 1;
    

    ... which fits your updated question.

    Note a subtle difference between count(*) and count(all_names). The former counts all rows, no matter what, while the latter only counts rows where all_names IS NOT NULL. If your column all_names is defined as NOT NULL, both return the same, but count(*) is a bit shorter and faster.

    About GROUP BY 1:

    • GROUP BY + CASE statement
    0 讨论(0)
提交回复
热议问题