[英]MYSQL case statement with sum query
Not sure if this is possible - but I am trying to do the following Have a table with following colums 不知道这是否可能-但我正在尝试执行以下操作
vote_id (primary_key)
question_id
user_id
vote_count
This basically stores all the votes casted by users for a particular question 这基本上存储了用户对特定问题的所有投票
Now in a single query is it possible for me to get the total vote count and check if a particular user has casted his vote or not. 现在,在一个查询中,我就有可能获得总投票数并检查特定用户是否投票。
Something along these lines - lets say for user_id 10 这些内容-假设user_id 10
SELECT sum(vote),
(
CASE
WHEN (user_id = 10)
THEN user_id
ELSE NULL
END
) user_id
FROM vote_question
GROUP BY course_question_id
This obviously doesn't work. 这显然行不通。
What I'm expecting is if a particular user has voted - his user_id should be returned along with vote count - if he not voted - return null 我期望的是特定用户是否已投票-他的user_id应该与投票计数一起返回-如果他未投票-返回null
Thanks 谢谢
That will be: 那将是:
SELECT
SUM(vote),
COUNT(IF(user_id = 10, 1, NULL)) AS has_user_id_10,
FROM
vote_question
GROUP BY
course_question_id
-this will result with has_user_id_10
greater than zero if user with id 10 cast his vote, and zero - if not. -如果ID为10的用户投票,则
has_user_id_10
大于零,否则为零;否则,结果为零。 May be you want strict 1
or 0
, then simply replace that with 可能是您想要严格的
1
或0
,然后将其替换为
COUNT(IF(user_id = 10, 1, NULL))>0 AS has_user_id_10
Please try this - 请尝试这个-
select user_id, vote_count
from
(
select sum(vote) vote_count ,user_id, course_question_id from vote_question group by user_id, course_question_id
)
where vote_count <>0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.