您可以使用如下的交叉表功能;
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:函數crosstab(未知),則應該運行此操作;
CREATE EXTENSION tablefunc;
交叉表在SQL本身就很複雜,因爲這不是如何SQL的作品。執行查詢之前,查詢的列數必須知道**。所以做交叉表的最好方法是在應用程序層。 –