Dynamically generate columns in PostgreSQL

后端 未结 1 1209
无人共我
无人共我 2021-01-05 06:11

I have seen that there are quit a few similar questions like this one, but I havent understood how to code it myself. Please have in mind that I am just a beginner in this f

相关标签:
1条回答
  • 2021-01-05 06:54

    The basic crosstab query for your example is simple:

    SELECT * FROM crosstab(
           'SELECT zoom, day, point
            FROM   province
            ORDER  BY 1, 2'
    
         , $$VALUES ('2015-10-01'::date), ('2015-10-02')$$)
    AS ct (zoom text, day1 int, day2 int);
    

    But not with dynamic column names or a dynamic number of columns. As a compromise, you can have a fixed number of columns and only fill the leading ones. Basics:

    • PostgreSQL Crosstab Query

    Dynamic?

    crosstab_hash is not going to help you with dynamic column names. It's for repeated use without typing a column definition list, but not for dynamic column names. Examples:

    • Dynamically generate columns for crosstab in PostgreSQL
    • Sql: Transposing rows into columns

    For truly dynamic column names, you need two round trips to the server. Whether you retrieve the column names with a first query to build a second query, or you create a cursor or a temporary table or a prepared statement. Whatever you try, you need two round trips. SQL wants to know the return type at call time.

    The closest I could get to a "dynamic" call is with my custom crosstab_n() function defined in this related answer:

    • Dynamic alternative to pivot with CASE and GROUP BY

    Or you give up the idea of a completely dynamic crosstab query (because, you know, it's impossible) and use a two-step workflow, like mentioned above.

    1. Let a function generate the crosstab query text. You can use the function provided here (and adapt it to your needs!):

      • Execute a dynamic crosstab query

      In particular, remove GROUP BY 1, 2, since you do not aggregate rows before the cross tabulation.

    2. Execute the generated function.


    For completeness, there is also the new \crosstabview metacommand in psql in Postgres 9.6 (just released) - with similar functionality, and it can display dynamic column names (attaching dynamic names happens in the psql client, not in the Postgres server).

    0 讨论(0)
提交回复
热议问题