Postgres交叉表查询

时间:2015-07-05 10:31:26

标签: sql postgresql

我有一个表,它有7个不同的类,区域值。

        Image image = null;
        URL url = new URL(urlAdr);
        InputStream in = new BufferedInputStream(url.openStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int n = 0;
        while (-1!=(n=in.read(buf)))
        {
           out.write(buf, 0, n);
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();
        FileOutputStream fos = new FileOutputStream(directoryToSave);
        fos.write(response);
        fos.close();

但是我希望以每个不同的pid | class| area | ----+------+------+ 2 | 1 | 10 | 2 | 2 | 10 | 2 | 6 | 20 | 4 | 1 | 30 | 4 | 2 | 40 | 4 | 3 | 50 | 4 | 4 | 60 | 4 | 5 | 70 | 9 | 6 | 80 | 11 | 1 | 90 | 11 | 4 | 10 | 11 | 7 | 20 | 作为列标题的格式呈现此数据,然后让每行对应一个类区域(即第一行是每个{{1级的区域) 1}})。

pid

是否可以在PostgreSQL中创建这样的输出?

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
    SUM(CASE WHEN pid = 2 THEN area ELSE 0 END) As "2",
    SUM(CASE WHEN pid = 4 THEN area ELSE 0 END) As "4",
    SUM(CASE WHEN pid = 9 THEN area ELSE 0 END) As "9",
    SUM(CASE WHEN pid = 11 THEN area ELSE 0 END) As "11"
FROM t
GROUP BY class
ORDER BY class
相关问题