Postgres交叉表将值分配到错误的列中

5

我有一个示例表格名为 antest,如下所示,用于测试 crosstab 函数。

create table antest(student text, subject text, result numeric);
insert into antest(student, subject, result) values
('peter','music',2.0), 
('peter','language',2.0),
('gabriel','history',8.0),
('john','history',9.0),
('john','maths',4.0),
('john','music',7.0);

student|subject|result
-------+-------+------
peter  |music  |2.0
peter  |lanuage|2.0
gabriel|history|8.0
john   |history|9.0
john   |maths  |4.0
john   |music  |7.0

期望的结果:

student|music|language|history|maths
-------+-----+--------+-------+-----
peter  |2.0  |2.0     |       |
gabriel|     |        |8.0    |
john   |7.0  |        |9.0    |4.0

我已经执行了以下查询:

我已经执行了以下查询:

select * 
from public.crosstab (
    'select student, subject, result from antest',
    'select distinct subject from antest'
) as final_result(student text, music numeric, maths numeric, history numeric, language numeric);

我得到了以下结果:
student|music|maths|history|language
-------+-----+-----+-------+--------
peter  |2.0  |     |       |2.0
gabriel|     |8.0  |       |
john   |7.0  |9.0  |4.0    |

请告诉我我犯了什么错误。

我需要为另一个30GB大小并具有约75个属性的数据库重复此查询。是否有自动化的可能性?


请发布“CREATE TABLE”和“INSERT INTO”以重新创建您的案例。 - Lukasz Szozda
@Iad2025编辑了这个问题。结果甚至没有按1排序。 - Mike
2个回答

5

在分类查询和列定义中,必须确保分类的顺序完全相同。因为您想要一个任意选择的(不是按字母顺序)顺序,所以应该在分类查询中使用values

select * 
from crosstab (
    $q$ select student, subject, result from antest $q$,
    $q$ values ('music'), ('language'), ('history'), ('maths') $q$
) as final_result(student text, music numeric, language numeric, history numeric, maths numeric);


 student | music | language | history | maths 
---------+-------+----------+---------+-------
 peter   |   2.0 |      2.0 |         |      
 gabriel |       |          |     8.0 |      
 john    |   7.0 |          |     9.0 |   4.0
(3 rows)

当然,你可以在查询语句中使用order by,但这时你必须更改列定义中的顺序。
select * 
from crosstab (
    $q$ select student, subject, result from antest $q$,
    $q$ select distinct subject from antest order by 1 $q$
) as final_result(student text, history numeric, language numeric, math numeric, music numeric);

 student | history | language | math | music 
---------+---------+----------+------+-------
 peter   |         |      2.0 |      |   2.0
 gabriel |     8.0 |          |      |      
 john    |     9.0 |          |  4.0 |   7.0
(3 rows)    

这个有效,谢谢。如果我想按字母顺序排列并且有大约75个属性怎么办? - Mike
明白了。如果想要它们基本上按字母顺序排列,谢谢。 - Mike

-2
Telmo, 葡萄牙,Aveiro 医院:今天出现了同样的问题;从来没有使用过 crosstab(),只用了 case when;它运行得很好。

2
工作得很好吗? - starball
1
根据目前的写法,你的回答不够清晰。请编辑以添加更多细节,帮助其他人理解这如何回答所提出的问题。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接