2014-09-29 73 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