2011-07-06 51 views
-1

嗨我想編寫一個mysql查詢,給出一個條件明智的結果。例如如何寫條件明智的結果提供查詢?

。我有一個問題,答案值,用戶選擇值字段的表。

用戶可以參加多次回答該問題。

 
qid  rightanz  wronganz 
11   4    2 
11   4    4 
11   4    1 
25   1    1 

I want out put like this 
qid  rightanz  wronganz 
11   1   2 
25   1   0 

我想顯示多少次的用戶提供了這個問題,正確和錯誤的答案? 我該如何寫一個mysql查詢呢?任何機構都可以幫助我?

+0

這將是非常有益的如果您可以提供表格模式以及如何在表格中設置這些列。 – rajasaur

回答

2

對於所有問題

SELECT a.userId, q.qid 
,SUM(CASE WHEN q.answer = a.answer THEN 1 ELSE 0 END) AS correct_answers 
,SUM(CASE WHEN q.answer = a.answer THEN 0 ELSE 1 END) AS wrong_answers 
FROM questions q 
JOIN answers a ON q.qid = a.qid 
GROUP BY a.userId, q.qid 

對於一個具體的問題

SELECT a.userId 
,SUM(CASE WHEN q.answer = a.answer THEN 1 ELSE 0 END) AS correct_answers 
,SUM(CASE WHEN q.answer = a.answer THEN 0 ELSE 1 END) AS wrong_answers 
FROM questions q 
JOIN answers a ON q.qid = a.qid 
WHERE q.qid = <question_id> 
GROUP BY a.userId 
+0

感謝您的幫助,其工作正常:) – learner

+0

不用謝! – niktrs

2
SELECT SUM(IF(answer = 42, 1, 0)) AS correct_count, count(*) as total_count 
FROM answers 
WHERE user_id = 13 

假設user_id要檢查是13,正確答案是42

+2

這裏有一個提示:'SUM(IF(answer = 42,1,0))'更優雅地表示爲'SUM(answer = 42)' – Bohemian

+0

@Bohemian:太棒了 – zerkms