2016-10-27 13 views
0

私のテーブルはこのようになります(「id_country」の下にリストされている250個の国と「年」の下で50年の):Postgresに多数のエントリがあるテーブルをクロス集計する方法は?

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

、これはどのようにSQL作品ではないので、クロス集計はSQLで本質的に複雑です。クエリの列数は、**クエリが実行される前に**知っていなければなりません。したがって、クロス集計を行う最善の方法はアプリケーション層にあります。 –

答えて

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); 

エラーが発生した場合は、関数クロス集計(不明)を実行してください。

CREATE EXTENSION tablefunc; 

enter image description here

関連する問題