postgresql - 如何在 PostgreSQL 中进行透视

标签 postgresql pivot postgresql-9.1

我是 PostgreSQL 的新手。

假设我有一个如下所示的表格

colorname   Hexa    rgb rgbvalue
Violet  #8B00FF r   139
Violet  #8B00FF g   0
Violet  #8B00FF b   255
Indigo  #4B0082 r   75
Indigo  #4B0082 g   0
Indigo  #4B0082 b   130
Blue    #0000FF r   0
Blue    #0000FF g   0
Blue    #0000FF b   255

如果我在 SQL Server 中执行数据透视

SELECT colorname,hexa,[r], [g], [b]
FROM
(SELECT colorname,hexa,rgb,rgbvalue
    FROM tblPivot) AS TableToBePivoted
PIVOT
(
sum(rgbvalue)
FOR rgb IN ([r], [g], [b])
) AS PivotedTable;

我得到的输出为

colorname   hexa    r   g   b
Blue    #0000FF 0   0   255
Indigo  #4B0082 75  0   130
Violet  #8B00FF 139 0   255

如何使用 PostgreSQL 做同样的事情?

我的尝试是

SELECT *
FROM crosstab
(
    'SELECT 
        colorname
        ,hexa
        ,rgb
        ,rgbvalue
    FROM tblPivot'
)AS ct(colorname text, hexa text, rgb text, rgbvalue int);

但是出现错误:

ERROR:  function crosstab(unknown) does not exist
LINE 2: FROM crosstab
             ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
********** Error **********
ERROR: function crosstab(unknown) does not exist**

在 PostgreSQL 中是否有任何优雅的方法(任何内置函数...)这样做的标准做法是什么?

最佳答案

运行这个

CREATE EXTENSION tablefunc;

并尝试执行你的查询

关于postgresql - 如何在 PostgreSQL 中进行透视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7563796/

相关文章:

postgresql - 像 excel 一样创建 Postgres Pivot

sql - 将表中的数据合并到一行 T-SQL

SQL - 不同类别的列

仅在 Linux 上的 PostgreSQL 密码验证失败

Postgresql服务器远程连接

postgresql - 在 jsonb 列 postgresql9.5 上创建 gin 索引时出错

linux - 为什么 PostgreSQL 的 shell 显示不同的操作系统版本而不是我的真实操作系统?

sql - 使用其他列从 JSONB 列获取数据

postgresql - PostgreSQL 中 MS SQL Server 的 GROUP BY ...WITH ROLLUP 的替代方案?

python - SQLAlchemy:过滤多对多但返回所有结果