我希望能够选择所有回复'Crunchy'的人并回答'直接'并将其作为回答'Crunchy'的所有用户的百分比返回。
最终游戏是能够产生一个事实,例如'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 = %
到目前为止,我有一个查询来选择所有回复Crunchy的用户并回答了Straight:
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查询的其余部分,还是有更简单的方法来解决这个问题?
答案 0 :(得分: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
列与NULL
没有匹配的行时,a2
会返回answer = 'Straight'
。并且COUNT(a2.user_id)
仅计算非空值,因此这会计算回答Straight
的所有用户。同时,COUNT(*)
计算所有行,即所有Crunchy
个答案。
如果没有Crunchy答案,IF()
可以防止除以0。