Unable to use crosstab in Postgres

后端 未结 3 751
北荒
北荒 2021-02-14 01:16

Postgres 9.2.1 on OSX 10.9.2.

If I run the following crosstab example query:

CREATE EXTENSION tablefunc; 

CREATE TABLE ct(id SERIAL, rowid TEXT, attribu         


        
相关标签:
3条回答
  • 2021-02-14 01:52

    You can change the first line into:

    CREATE EXTENSION IF NOT EXISTS tablefunc;
    
    0 讨论(0)
  • 2021-02-14 01:55

    There's a misconception in your answer:

    and not accessible to all schemas in it.

    All schemas inside the same database are accessible to all sessions in that same database, (as long as privileges are given). It's a matter of setting the search_path. Schemas work much like directories / folders in the file system.

    Alternatively, you can schema-qualify the function (and even operators) to access it independently of the search_path:

    SELECT *
    FROM my_extension_schema.crosstab(
        $$select rowid, attribute, "value"
          from   ct
          where  attribute IN ('att2', 'att3')
          order  by 1,2$$
       ,$$VALUES ('att2'), ('att3')$$
       ) AS ct(row_name text, category_2 text, category_3 text);

    Recent related answer with more Info:
    How to use % operator from the extension pg_trgm?

    Dubious crosstab()

    Your query returned attributes 'att2' and 'att3', but the column definition list had three categories (category_1, category_2, category_3) that do not match the query.
    I removed category_1 and added the second parameter to crosstab() - the "safe" version. More details here:
    PostgreSQL Crosstab Query

    Aside: Don't use value as column name. Even if Postgres tolerates it. It's a reserved word in standard SQL.

    0 讨论(0)
  • 2021-02-14 02:01

    the problem in my case was that the 'tablefunc' extension was defined on one specific schema in my DB, and not accessible to all schemas in it.

    [edit: as explained above, 'not accessible to all schemas' should read 'cannot be loaded on all schemas']

    I learned that:

    1. the Extension can only be loaded into one schema - so load it into 'public'
    2. you have to manually drop the extension from one schema before you can load it in another
    3. you can list the loaded extensions per schema in pqsl using the command: \df *.crosstab

    [edit: 4. you can access the extension either by search_path, by loading it on public schema or by explicitly specifying a schema]

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