PostgreSQL中的交叉表查询

时间:2013-03-12 01:20:55

标签: sql postgresql case postgresql-9.1 crosstab

我想在交叉表中查询此查询的结果:

SELECT district, sex ,count(sex)
FROM table1
GROUP BY sex, district
ORDER BY district;

district | sex | count
---------+-----+-----
dis_1    | M   | 2
dis_1    | F   | 4
dis_1    | NI  | 1
dis_2    | M   | 5
dis_2    | F   | 2

像这样:

district | M | F | NI
---------+---+---+---
dis_1    | 2 | 4 | 1
dis_2    | 5 | 2 | 0

我做了一些测试没有成功,如下面的查询:

SELECT  row_name AS district,
        category_1::varchar(10) AS m,
        category_2::varchar(10) AS f,
        category_3::varchar(10) AS ni,
        category_4::int AS count

FROM crosstab('select district, sex, count(*)
               from table1 group by district, sex')
     AS ct  (row_name varchar(27), 
             category_1 varchar(10), 
             category_2 varchar(10), 
             category_3 varchar(10),
             category_4 int);

2 个答案:

答案 0 :(得分:4)

此交叉表功能完全按照您的要求生成(简化数据类型除外):

SELECT *
FROM   crosstab('
         SELECT district, sex, count(*)::int
         FROM   table1
         GROUP  BY 1,2
         ORDER  BY 1,2'
        ,$$VALUES ('M'), ('F'), ('NI')$$)
AS ct (district text
      ,"M"      int
      ,"F"      int
      ,"NI"     int);

您尝试时遇到了一些错误 在这个密切相关的答案中查找详细信息和解释:
PostgreSQL Crosstab Query

答案 1 :(得分:3)

您可以使用带有CASE表达式的聚合函数来获得列中的结果:

select district,
  sum(case when sex ='M' then 1 else 0 end) M,
  sum(case when sex ='F' then 1 else 0 end) F,
  sum(case when sex ='NI' then 1 else 0 end) NI
from table1
group by district
order by district
相关问题