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
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
select COUNT(*) from ratings WHERE upvote=true AND TopicID = :topicsID ?
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.