English 中文(简体)
How to do Pivoting in PostgreSQL
原标题:How to do Pivoting in 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

如果我在服务器中做一个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;

我的产出是一样的。

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

如何使用邮政总局?

My attempt is

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**

Is there any elegant way of doing so in PostgreSQL (any built in function...) What is the standard practice of doing so ?

最佳回答

这可以作为一个联合网络表达:

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 
;
问题回答

执行

CREATE EXTENSION tablefunc;

页: 1





相关问题
摘录数据

我如何将Excel板的数据输入我的Django应用? I m将PosgreSQL数据库作为数据库。

Postgres dump of only parts of tables for a dev snapshot

On production our database is a few hundred gigabytes in size. For development and testing, we need to create snapshots of this database that are functionally equivalent, but which are only 10 or 20 ...

How to join attributes in sql select statement?

I want to join few attributes in select statement as one for example select id, (name + + surname + + age) as info from users this doesn t work, how to do it? I m using postgreSQL.

What text encoding to use?

I need to setup my PostgreSQL DB s text encoding to handle non-American English characters that you d find showing up in languages such as German, Spanish, and French. What character encoding should ...

SQL LIKE condition to check for integer?

I am using a set of SQL LIKE conditions to go through the alphabet and list all items beginning with the appropriate letter, e.g. to get all books where the title starts with the letter "A": SELECT * ...

热门标签