gpt4 book ai didi

PostgreSQL 9.3 : Crosstab query

转载 作者:行者123 更新时间:2023-11-29 13:28:53 26 4
gpt4 key购买 nike

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

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"

最佳答案

也许这就是你想要的?

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

关于PostgreSQL 9.3 : Crosstab query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28448374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com