Jump to content

[SOLVED] SUM with WHERE question


ViperSBT

Recommended Posts

SELECT d.dnumber, SUM( p.points ) AS points
FROM dogs d
JOIN points p ON d.dnumber = p.dog
WHERE points >=20000
GROUP BY p.dog

 

This should be fairly obvious, I am summing all of the points for each dog in my table.  In doing so I only want to have results returned for dogs that have more than 20,000 points.  For some reason when I use this, I get no lines returned.  If I take out the WHERE I get everything...

 

And, yes, there are lines that have well more than 20,000 points returned.

Link to comment
https://forums.phpfreaks.com/topic/46527-solved-sum-with-where-question/
Share on other sites

To apply a condition to an aggregated result (such as sum(), count(), max(), min()), you need to use HAVING instead of WHERE.

 

The reason is that WHERE is applied before the sum is calculated, and HAVING is applied afterwards.

 

SELECT d.dnumber, SUM( p.points ) AS points
FROM dogs d
JOIN points p ON d.dnumber = p.dog
GROUP BY p.dog
HAVING SUM(p.points) >= 20000

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.