2016-12-13 87 views
3

我希望能夠選擇所有回答「脆脆」的人,並回答「直」,並以所有回答「脆脆」的用戶的百分比形式返回。根據多個選擇語句查詢用戶的百分比

最終的遊戲就是能夠產生一個事實,比如'70%的回答Crunchy的用戶也回答了Straight'。

|id |question_id | user_id | answer | 
|-------------------------------------| 
|1 | 1  | 81  | Crunchy | 
|2 | 1  | 82  | Crunchy | 
|3 | 1  | 83  | Smooth | 
|4 | 2  | 81  | Straight | 
|5 | 2  | 82  | Diagonal | 
|6 | 2  | 83  | Diagonal | 

僞代碼將是類似以下內容:

((Select all unique users where answer === Crunchy && where answer === Straight) 

/

(Select all unique users where answer === Crunchy)) 

* 100 = % 

到目前爲止,我有一個查詢,選擇誰回答脆脆的,也回答了直所有用戶:

SELECT * 
    FROM 
    ((SELECT *  
     FROM answers 
     WHERE (question_id = 1 AND answer = 'Crunchy')) A 

    JOIN 

    (SELECT *  
     FROM answers 
     WHERE (question_id = 3 AND answer = 'Straight')) B 

    ON A.user_id = B.user_id) 
    GROUP BY A.user_id 

這將選擇所有同時選擇了兩個答案的用戶,但我需要將它作爲一個總和,這樣我就可以將它除以第二個查詢,它將與第一個查詢相同,但沒有連接,所以本質上是這樣的;

SELECT *  
     FROM answers 
     WHERE (question_id = 1 AND answer = 'Crunchy' 

,然後乘以的由100

答案如何完成這個SQL查詢的其餘部分還是有一個更簡單的方法來進行此事?

回答

2

您可以使用LEFT JOIN來關聯它們。

SELECT IF(COUNT(*) = 0, 0, COUNT(a2.user_id)/COUNT(*)*100) AS percentage 
FROM answers AS a1 
LEFT JOIN answers AS a2 ON a1.user_id = a2.user_id 
    AND a2.question_id = 2 AND a2.answer = 'Straight' 
WHERE a1.question_id = 1 AND a1.answer = 'Crunchy' 

LEFT JOIN將返回NULLa2列時沒有匹配的行與answer = 'Straight'。並且COUNT(a2.user_id)只計算非空值,因此這將對所有回答了Straight的用戶進行計數。同時,COUNT(*)統計所有行,這全部是Crunchy答案。

IF()如果沒有Crunchy答案,可以防止0除法。

+1

這正是我所需要的。感謝Barmar。我最初的想法也更加簡潔。 – Stretch0