简体   繁体   中英

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

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

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. May be you want strict 1 or 0 , then simply replace that with

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM