如何在Postgres中交叉表中包含许多条目?

时间:2016-10-27 08:39:03

标签: postgresql crosstab

我的表格如下(其中250个国家/地区列在" id_country"以及50年以下"年和#34;):

    id_country  year    value
        4       2000      5
        4       2001      6
        4       2002      4
        4       2003      8
        8       2000      7
        8       2001      6
        8       2002      9
        8       2003      3
        12      2000      6
        12      2001      4
        12      2002      7
        12      2003      5

我想通过查询将此转换为此

          4    8    12    16   ...
  2000    5    7    
  2001    6
  2003    4
  2004    8
   ...

我通过循环完成了与PHP类似的操作,但这有点奇怪。我想知道是否有更直接和流畅的Postgres-SQL方法。没有Postgres功能也许不可能?遗憾的是,我不是这方面的专家。

1 个答案:

答案 0 :(得分:0)

你可以使用如下的交叉表功能;

CREATE TABLE "test1"
(
  id_country integer NOT NULL,
  year text NOT NULL,
  value integer
)

INSERT INTO test1 (id_country,year,value) VALUES (4,'2000', 5);
INSERT INTO test1 (id_country,year,value) VALUES (4,'2001', 6);
INSERT INTO test1 (id_country,year,value) VALUES (4,'2002', 4);
INSERT INTO test1 (id_country,year,value) VALUES (4,'2003', 8);
INSERT INTO test1 (id_country,year,value) VALUES (8,'2000', 7);
INSERT INTO test1 (id_country,year,value) VALUES (8,'2001', 6);
INSERT INTO test1 (id_country,year,value) VALUES (8,'2002', 9);
INSERT INTO test1 (id_country,year,value) VALUES (8,'2003', 3);
INSERT INTO test1 (id_country,year,value) VALUES (12,'2000', 6);
INSERT INTO test1 (id_country,year,value) VALUES (12,'2001', 4);
INSERT INTO test1 (id_country,year,value) VALUES (12,'2002', 7);
INSERT INTO test1 (id_country,year,value) VALUES (12,'2003', 5);


SELECT *
FROM crosstab(
  'select year, id_country, value
   from test1
   order by 1,2')
AS ct(year text, "4" int, "8" int, "12" int);

如果你得到ERROR:函数交叉表(未知),你应该运行它;

CREATE EXTENSION tablefunc;

enter image description here