使`group by`导致多列

时间:2015-12-28 20:52:07

标签: 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

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

如果已知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

答案 1 :(得分:0)

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