从查询中获取列定义列表

时间:2017-08-16 18:23:52

标签: postgresql crosstab table-functions

我有什么:

两个postgres表,一个包含数据,一个包含要聚合的组。两个表都可以更改,例如它计划稍后添加位置,并定义新的类别。

locations:
| id | zipcode | name    | type   |
|----+---------+---------+--------|
|  1 |    1234 | Burger1 | burger | 
|  2 |    1234 | Burger2 | burger |
|  3 |    1234 | Gas1    | gas    |
|  4 |    5678 | FriesA  | fries  |
|  5 |    9876 | FriesB  | fries  |
|  6 |    9876 | GarageA | garage |

categories:
| category | item   |
|----------+--------|
| food     | burger | 
| food     | fries  |
| car      | gas    | 
| car      | garage | 

我期望得到什么: 每个邮政编码的设施数量,按给定类别汇总:

result:
| zipcode | cnt(food) | cnt(car) |
|---------+-----------+----------|
|    1234 |         2 |        1 | 
|    5678 |         1 |          |
|    9876 |         1 |        1 |

我尝试了什么: 使用postgres的交叉表() - 函数来旋转表格:(见https://www.postgresql.org/docs/current/static/tablefunc.html#AEN186219)。

不幸的是,crosstab()的返回类型是记录,因此您需要定义显式列定义。为了允许稍后添加类别,我试图从查询中获取列定义列表:

SELECT * FROM crosstab(
    'SELECT location.zipcode, categories.category, count(location.id)
    FROM locations
    JOIN categories
    ON categories.item = location.type
    GROUP BY zipcode, categories.category'
    ,
    'SELECT DISTINCT category FROM categories ORDER BY category ASC;')
AS
    ct(
        SELECT array_to_string(
            array_cat(
                array(SELECT 'zipcode varchar'::varchar),
                array(SELECT DISTINCT (category || ' int')::varchar AS category FROM categories ORDER BY category ASC)
            ),
        ', '
        )
    );

问题是什么

Postgres不接受查询作为列定义列表。如果可能的话,我想避免使用PL \ pgSQL函数,而只使用“常规”查询:

ERROR:  syntax error at or near »select«
LINE 16:   select array_to_string(
           ^

1 个答案:

答案 0 :(得分:0)

course_running