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
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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.