Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top