0
upVote   DownVote
|true   | 0
|true   | 0
|0      | true
|true   | 0
|true   | 0
|0      | true

I have columns like this above in my sql table. I want to count the total number of upVotes - Downvotes just like stackOverflow. But for some reason I am having hard time with sql syntax.

SELECT COALESCE(sum(CASE WHEN upvote THEN 1 ELSE 0 END),0) from Ratings WHERE TopicID = :topicsID

I have seen the above sql query example somewhere but not sure I am heading in the right direction.Help is appreciated

11
  • What is the issue with your query? Your on the right track, but clearly only counting upvotes. Commented Apr 9, 2018 at 15:13
  • 1
    Can you ever have true | true or false | false ? Commented Apr 9, 2018 at 15:13
  • 4
    Since MySQL booleans are integers, simply use SUM(upVote) Commented Apr 9, 2018 at 15:14
  • 2
    IMHO the table's structure is a little bit meeh... One upvote column with a boolean value is enough. Commented Apr 9, 2018 at 15:21
  • 1
    What do you mean by compare the downvote, you can count all upvotes, then count all downvotes. Commented Apr 9, 2018 at 15:23

2 Answers 2

3

I guess you need to subtract on sum(upvote) and sum(DownVote)

SELECT sum(upvote) - sum(DownVote)
from Ratings 
WHERE TopicID = :topicsID

Fiddle: http://sqlfiddle.com/#!9/b1644c/8

I think One vote column with a boolean value is enough.

Because True can mean upvote,False can mean DownVote

CREATE TABLE Ratings
(
    Vote BOOL
);
INSERT INTO Ratings VALUES 
(TRUE),
(TRUE),
(0),
(0),
(TRUE),
(TRUE),
(0);

SELECT sum(CASE WHEN Vote THEN 1 ELSE 0 END) - 
   sum(CASE WHEN Vote THEN 0 ELSE 1 END) as vote
from Ratings 
WHERE TopicID = :topicsID

Fiddle: http://sqlfiddle.com/#!9/727c2b/3

Sign up to request clarification or add additional context in comments.

1 Comment

I edited this to remove the blockquotes (along with other answers of yours containing them). Those have a special use and not to be used as a personal formatting preference. This matter has been discussed on meta a few times. So, can you please stop using those?
0
select COUNT(*) from ratings WHERE upvote=true AND TopicID = :topicsID ?

2 Comments

but how would I compare and decrease the count when there is a downVote?
didnt know thats what you were aiming for but you could run the same query for false and then subtract true-false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.