[英]How to make the equivalent of DISTINCT in query counting results
我的表存儲了一組調查結果,我將使用以下查詢將其輸出到結果頁面:
SELECT a.question_one AS answer, q1.ct AS q1_count, q2.ct AS q2_count, q3.ct AS q3_count
FROM vote_entries
AS a
INNER JOIN (SELECT question_one, count(question_one) AS ct from vote_entries group by question_one) q1 on q1.question_one=a.question_one
INNER JOIN (SELECT question_two, count(question_two) AS ct FROM vote_entries group by question_two) q2 on q2.question_two=a.question_one
INNER JOIN (SELECT question_three, count(question_three) AS ct FROM vote_entries group by question_three) q3 on q3.question_three=a.question_one
GROUP BY a.question_one
這可以達到我想要的效果,但是我剛剛注意到有些人從同一電子郵件地址提交了不止一次的郵件。 我想過濾掉這些人,以便只包括他們的回應之一。
本質上,我想擁有類似WHERE DISTINCT email
,但是當然不存在。 有誰知道我可以實現我想要做的事情,最好是在這個查詢中?
這是我的表結構:
CREATE TABLE IF NOT EXISTS `vote_entries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(128) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
`name` varchar(128) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
`question_one` varchar(32) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
`question_two` varchar(32) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
`question_three` varchar(32) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
數據示例如下所示。 用戶可以為每個問題選擇單選按鈕中的三個選項之一。
+----+------------------+------------+--------------+--------------+----------------+
| id | email | name | question_one | question_two | question_three |
+----+------------------+------------+--------------+--------------+----------------+
| 1 | test@email.com | John Doe | RIC | RIC | RIC |
| 2 | test2@email.com | Jane Smith | BAR | BAR | BAR |
| 3 | test2@email.com | Jane Smith | BAR | BAR | BAR |
| 4 | sample@email.com | Kelly Doe | Existing | Existing | Existing |
+----+------------------+------------+--------------+--------------+----------------+
問題是,如果簡·史密斯(Jane Smith)提交她的答案兩次,將會不公平地歪曲結果。 但是,我也不想鼓勵人們制作虛假的電子郵件地址來提交多次,因此,我不希望使用某種前端解決方案。
我建議條件聚合。 這可能是一種執行所需操作的簡單方法:
select a.answer,
count(distinct case when a.answer = ve.question_one then ve.email) as q1_count,
count(distinct case when a.answer = ve.question_two then ve.email) as q2_count,
count(distinct case when a.answer = ve.question_three then ve.email) as q3_count
from (select distinct ve.question_one as answer
from vote_entries ve
) a cross join
vote_entries ve
group by a.answer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.