gpt4 book ai didi

PostgreSQL:将 2 列结果集转换为单行表

转载 作者:行者123 更新时间:2023-11-29 12:26:49 26 4
gpt4 key购买 nike

努力实现我认为会是一个简单的操作...

编辑: 此处提供 SQLFiddle:http://sqlfiddle.com/#!15/11711/1/0

使用 PostgreSQL 9.4,假装我有一个返回这个两列集的查询:

CATEGORY | TOTAL
all | 14
soccer | 5
baseball | 6
hockey | 3

但是我更愿意将其旋转成单行集:

ALL | SOCCER | BASEBALL | HOCKEY
14 | 5 | 6 | 3

换句话说,我希望我所有的“CATEGORY”值都变成列,相应的“TOTAL”值放在相应列下的第一行。

我一直在尝试使用 CROSSTAB()... 但截至目前我收到以下错误:

错误:返回“记录”的函数需要列定义列表

作为引用,以下是我尝试作为我的 SQL 命令输入的内容:

SELECT * FROM crosstab(
$$
WITH "countTotal" AS (
SELECT text 'all' AS "sportType", COUNT(*) AS "total"
FROM log
WHERE type = 'SPORT_EVENT_CREATED'
GROUP BY "sportType"
),
"countBySportType" AS (
SELECT sport_type AS "sportType", COUNT(*) AS "total"
FROM log
WHERE type = 'SPORT_EVENT_CREATED'
GROUP BY "sportType"
)
SELECT * FROM "countTotal"
UNION
SELECT * FROM "countBySportType"
$$
)

最佳答案

我认为您必须指定输出列的名称和类型。来自 postgres 手册 tablefunc

The crosstab function is declared to return setof record, so the actual names and types of the output columns must be defined in the FROM clause of the calling SELECT statement, for example:
SELECT * FROM crosstab('...') AS ct(row_name text, category_1 text, category_2 text);

您必须使用 crosstabN(text) 才能将其与动态列数一起使用。这PostgreSQL Crosstab Query有关交叉表查询的大量详细信息。

还有一篇文章 Dynamic alternative to pivot with CASE and GROUP BY

关于PostgreSQL:将 2 列结果集转换为单行表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30501661/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com