我是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中是否有任何优雅的方式(任何内置函数......)这样做的标准做法是什么?
答案 0 :(得分:41)
运行此
CREATE EXTENSION tablefunc;
并尝试执行您的查询
答案 1 :(得分:5)
这可以表示为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'
;