sql - 使 `group by` 导致多列

标签 sql postgresql pivot crosstab

我有一个 (Postgres) 查询,其中包含一个常用的 group by 子句:

select extract(year from a.created) as Year,a.testscoreid, b.irt_tlevel, count(a.*) as Questions
from asmt.testscores a join asmt.questions b
on a.questionid = b.questionid
where a.answered = True
group by Year,a.testscoreid, b.irt_tlevel
order by Year desc, a.testscoreid

b.irt_tlevel 列的值为 lowmediumhigh,所有这些结果都在一个行格式,例如:

Year    TestScoreId    Irt_tlevel    Questions
2015    1              Low           2
2015    1              Medium        3
2015    1              High          5

我希望我的结果采用以下格式:

Year    TestScoreId    Low    Medium    High    TotalQuestions
2015    1              2      3         5        10

如有任何帮助,我们将不胜感激。

最佳答案

如果已知 irt_tlevel 列中不同值的数量是固定的,则可以使用条件聚合。

select 
extract(year from a.created) as Year,
a.testscoreid, 
sum(case when b.irt_tlevel = 'Low' then 1 else 0 end) as Low,
sum(case when b.irt_tlevel = 'Medium' then 1 else 0 end) as Medium,
sum(case when b.irt_tlevel = 'High' then 1 else 0 end) as High,
count(*) as Questions
from asmt.testscores a 
join asmt.questions b on a.questionid = b.questionid
where a.answered = True
group by Year, a.testscoreid
order by Year desc, a.testscoreid

关于sql - 使 `group by` 导致多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34500598/

相关文章:

sql - 从 SQL Server 检索压缩的 GZip 信息

mysql - 删除 MySQL 中字段具有重复数字的行

c++ - 使用 notify_listener - libpqxx

python - 如何旋转数据框

Mysql - Sum 在进行数据透视时不返回结果

sql - SQL Server 2000 中的行到列

sql - 仅在哪里查询?

mysql - MySQL 中的触发器 "BEFORE DELETE"

ruby-on-rails - Rails Migration 更改列以使用 Postgres 数组

django - 将小数字插入整数字段时出现 PostgreSql Integer out of range 错误