2

我有一张prefs桌子,下面是相关的列:

mydb=> SELECT pref_id, pref_name, pref_value FROM prefs;
 pref_id |  pref_name   |   pref_value
---------+--------------+----------------
       1 | PagerNumber  | 2125551234
       2 | PagerCarrier | @att.com
       3 | PagerCarrier | @something.com

我想制作这样的东西:

 section |  pager_number  | pager_carrier
---------+----------------+---------------
       1 | 2125551234     |
       2 |                | @att.com
       3 |                | @something.com

所以我使用了交叉表,按照stackoverflow上的这个例子:PostgreSQL Crosstab Query

SELECT row_name AS section,
       category_1::text AS pager_number,
       category_2::text AS pager_carrier
FROM crosstab('select pref_id::bigint, pref_name::text, pref_value::text
    FROM prefs')
AS ct (row_name bigint, category_1 text, category_2 text);

所有值都进入pager_number,并pager_carrier留空:

 section |  pager_number  | pager_carrier
---------+----------------+---------------
       1 | 2125551234     |
       2 | @att.com       |
       3 | @something.com |

谁能看到发生了什么?

4

2 回答 2

3

测试用例(提供样本数据的首选方式):

CREATE TEMP TABLE prefs (pref_id int, pref_name text, pref_value text);

INSERT INTO prefs VALUES 
 (1, 'PagerNumber' , '2125551234')
,(2, 'PagerCarrier', '@att.com')
,(3, 'PagerCarrier', '@something.com');

询问:

SELECT *
FROM   crosstab(
       'SELECT pref_id, pref_name, pref_value
        FROM   prefs
        ORDER  BY 1, 2',

       $$VALUES ('PagerNumber'::text), ('PagerCarrier')$$
       )
AS x (section text, pager_number bigint, pager_carrier text);

准确返回您的问题中描述的结果。如果 aPagerNumber可以不是有效bigint数字,请text改用。

您在问题中提到的答案已经过时,并且从一开始就永远不正确。我在那里添加了一个带有解释和链接的正确答案。

于 2012-08-01T03:30:16.943 回答
0

代替:

SELECT row_name AS section, category_1::text AS pager_number, category_2::text
AS pager_carrier
FROM crosstab('select pref_id::bigint, pref_name::text, pref_value::text
    FROM prefs')
AS ct (row_name bigint, category_1 text, category_2 text);

尝试:

SELECT *
FROM crosstab('select pref_id::bigint, pref_name::text, pref_value::text
FROM prefs ORDER BY 1,2')
AS prefs (row_name bigint, carrier_1 text, carrier_2 text);

如果你有:

    pref_id |  pref_name   |   pref_value
   ---------+--------------+----------------
   1 | PagerNumber  | 2125551234
   2 | PagerCarrier | @att.com
   3 | PagerCarrier | @something.com
   2 | PageNumber   | 2332323232
   3 | PagerCarrier | @somethingelse.com

你会得到:

    row_name |  carrier_1   |   carrier_2
   -----+--------------+----------------
   1 | 2125551234      |
   2 | @att.com        | 2332323232
   3 | @something.com  | @somethingelse.com

Postgress 交叉表参考

于 2012-08-01T00:12:49.897 回答