如何在PostgreSQL中进行透视

pri*_*kar 13 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
Run Code Online (Sandbox Code Playgroud)

如果我在SQL Server中做一个Pivot

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;
Run Code Online (Sandbox Code Playgroud)

我把输出作为

colorname   hexa    r   g   b
Blue    #0000FF 0   0   255
Indigo  #4B0082 75  0   130
Violet  #8B00FF 139 0   255
Run Code Online (Sandbox Code Playgroud)

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

我的尝试是

SELECT *
FROM crosstab
(
    'SELECT 
        colorname
        ,hexa
        ,rgb
        ,rgbvalue
    FROM tblPivot'
)AS ct(colorname text, hexa text, rgb text, rgbvalue int);
Run Code Online (Sandbox Code Playgroud)

但是输入错误:

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**
Run Code Online (Sandbox Code Playgroud)

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

Lax*_*nge 44

运行这个

CREATE EXTENSION tablefunc;
Run Code Online (Sandbox Code Playgroud)

并尝试执行您的查询

  • 如果我运行这个我得到`错误:扩展"tablefunc"已经存在`但是当我尝试使用它时,我得到`错误:函数交叉表(未知)不存在.我在Mac 10.9.2上使用Postgres 9.2.1.有任何想法吗? (3认同)
  • 确保使用\ c db_name连接到数据库,然后运行上面的命令. (3认同)

Sin*_*ion 7

这可以表示为JOIN:

SELECT c.colorname, c.hexa, r.rgbvalue, g.rgbvalue, b.rgbvalue
FROM (SELECT colorname, hexa
      FROM sometable
      GROUP BY colorname) c
JOIN sometable r ON c.colorname = r.colorname AND r.rgb = 'r'
JOIN sometable g ON c.colorname = g.colorname AND g.rgb = 'g'
JOIN sometable b ON c.colorname = b.colorname AND b.rgb = 'b'
;
Run Code Online (Sandbox Code Playgroud)

  • `crosstab()`属于`tablefunc`模块.您必须使用`CREATE EXTENSION`启用它.那说; 它提供的便利可能不是那么好; postgresql非常擅长优化连接,这种代码在更多数据库和更多开发人员中更容易识别. (7认同)