2014-09-29 67 views
0

我有以下3个选择查询返回2列设置。 有没有什么办法,quiznocorrectwrongnotattempted列马上就来类似以下内容:结合多个选择[group by]查询条件

quizno correct wrong notattempted 
1  80  10  10 
2  60  20  20 
3  100  0  0 

这些都是分离的查询:

select quizno, count(*) as correct from v_t1 where examid=96 AND result='correct' 
group by quizno order by count(*) desc 

select quizno, count(*) as wrong from v_t1 where examid=96 AND result='wrong' 
group by quizno order by count(*) desc 

select quizno, count(*) as notattempted from v_t1 where examid=96 AND result='notattempted' 
group by quizno order by count(*) desc 
+0

我建议看[JOIN](http://www.w3schools.com/sql/sql_join.asp)子句 – Grice 2014-09-29 16:07:02

回答

3

可以使用CASE聚集,并得到预期的输出

select quizno, 
     sum(case when result='correct' then 1 else 0 end) as 'correct', 
     sum(case when result='wrong' then 1 else 0 end) as 'wrong', 
     sum(case when result='notattempted' then 1 else 0 end) as 'notattempted' 
from v_t1 
where examid = 96 
group by quizno 
+1

+1打我毫秒;) – 2014-09-29 16:08:48

+0

这是非常快,像魅力工作。 – Zeeshanef 2014-09-29 16:18:25