PostgreSQL 9.3:交叉表查询

时间:2015-02-11 07:03:32

标签: postgresql postgresql-9.3 crosstab

我有一个叫做测试的表,它有四列,如下所示。

create table testing
(
cola varchar(10),
colb varchar(10),
colc varchar(10),
cold varchar(10)
);

插入一些行:

insert into testing values('A1','City1','X1','Z1'),
              ('A2','City2','X2','Z2'),
              ('A3','City3','X3','Z3'),
              ('A4','City4','X4','Z4');

预期结果:我想显示如下所示的结果:

cola  City1  City2  City3  City4  colc  cold
--------------------------------------------
A1      1      0      0      0     X1    Z1
A2      0      1      0      0     X2    Z2
A3      0      0      1      0     X3    Z3
A4      0      0      0      1     X4    Z4           

我的尝试:

我尝试使用以下脚本但收到错误。

select * from crosstab
(
'select cola,colb,count(colb),colc,cold from testing group by 1,2,4,5 order by 1,2,4,5',
'select distinct colb from testing'
)
as t
(
    cola varchar(10),City1 integer,City2 integer,City3 integer,City4 integer,colc varchar(10),cold varchar(10)
);  

错误详情

ERROR:  invalid input syntax for integer: "City1"

1 个答案:

答案 0 :(得分:1)

也许这就是你想要的?

select x1.*, x2.colc, x2.cold from crosstab
( $$select x1.cola, x2.colb,
     CASE WHEN x1.colb = x2.colb THEN 1 ELSE 0 END
    FROM testing x1 CROSS JOIN testing x2 
  $$
) AS x1( cola VARCHAR(10), City1 INT, City2 INT, City3 INT, City4 INT)
LEFT JOIN testing x2 ON x1.cola = x2.cola;

结果:

 cola | city1 | city2 | city3 | city4 | colc | cold 
------+-------+-------+-------+-------+------+------
 A1   |     1 |     0 |     0 |     0 | X1   | Z1
 A2   |     0 |     1 |     0 |     0 | X2   | Z2
 A3   |     0 |     0 |     1 |     0 | X3   | Z3
 A4   |     0 |     0 |     0 |     1 | X4   | Z4