Making `group by` result in multiple columns

亡梦爱人 提交于 2021-02-08 07:59:30

问题


I have a (Postgres) query with a usual group by clause:

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

The column b.irt_tlevel has values low, medium and high, all these results are in a row-format, for example:

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

I'd like my results to be in the following format:

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

Any help would be appreciated.


回答1:


You can use conditional aggregation if it is known that the number of distinct values in irt_tlevel column are fixed.

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



回答2:


select
    extract(year from a.created) as Year,
    a.testscoreid,
    b.irt_tlevel,
    count(Irt_tlevel = 'low' or null) as "Low",
    count(Irt_tlevel = 'medium' or null) as "Medium",
    count(Irt_tlevel = 'high' or null) as "High",
    count(a.*) as "TotalQuestions"
from
    asmt.testscores a
    join
    asmt.questions b on a.questionid = b.questionid
where a.answered
group by Year, a.testscoreid
order by Year desc, a.testscoreid


来源:https://stackoverflow.com/questions/34500598/making-group-by-result-in-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!