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.

有帮助吗?

解决方案

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.

其他提示

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top