Reputation: 569
I have this code (it works):
SELECT sportsID, newsID, cID, SUM(likes) AS totalLikes
FROM like_table
GROUP BY sportsID, newsID
ORDER BY totalLikes DESC
I tried to modify it to not show negative values, but it doesn't work.
SELECT sportsID, newsID, cID, SUM(likes) AS totalLikes
FROM like_table
WHERE totalLikes > 0
GROUP BY sportsID, newsID
ORDER BY totalLikes DESC
Can anyone help? I do not know what I'm doing wrong.
Upvotes: 0
Views: 249
Reputation: 18737
Try using HAVING
clause:
SELECT sportsID, newsID, cID, SUM(likes) AS totalLikes
FROM like_table
GROUP BY sportsID, newsID
HAVING SUM(likes)> 0
ORDER BY totalLikes DESC
Explanation:
The HAVING
clause was added to SQL because the WHERE
keyword could not be used with aggregate functions.
The WHERE
clause places conditions on the selected columns, whereas the HAVING
clause places conditions on groups created by the GROUP BY
clause.
Upvotes: 3
Reputation: 3907
WHERE totalLikes > 0
should be HAVING SUM(likes) > 0
and be placed after the GROUP BY clause. Thus:
SELECT sportsID, newsID, cID, SUM(likes) AS totalLikes
FROM like_table
GROUP BY sportsID, newsID
HAVING SUM(likes) > 0
ORDER BY totalLikes DESC
Upvotes: 2