1

The following SELECT statement results this

SELECT ProductID, SUM(Quantity) AS Quantity
FROM Production.ProductInventory
WHERE ProductID NOT IN (1001)
GROUP BY ProductID;

enter image description here

How come the edited SELECT statement below does not produce anything?

SELECT ProductID, SUM(Quantity) AS Quantity
FROM Production.ProductInventory
WHERE Quantity >= 1800
GROUP BY ProductID;

enter image description here

2
  • 1
    Are you serious? None of the sums that you have shown exceed 1800. If the value is always non-negative, then I wouldn't expect such large values. Commented Sep 24, 2018 at 16:19
  • @GordonLinoff There are sums larger than 1800 just can't see in the image as the list goes down a lot Commented Sep 24, 2018 at 16:19

2 Answers 2

6

You added WHERE clause:

SELECT ProductID, SUM(Quantity) AS Quantity
FROM Production.ProductInventory
WHERE Quantity >= 1800  -- no single row with Quantity that is higher than 1800
GROUP BY ProductID;

You probably want to filter values after aggregation:

SELECT ProductID, SUM(Quantity) AS Quantity
FROM Production.ProductInventory
GROUP BY ProductID
HAVING SUM(Quantity) >= 1800;   -- HAVING instead of WHERE

Filtering:

  • WHERE - before aggregation
  • HAVING - after aggregation
Sign up to request clarification or add additional context in comments.

Comments

0

The WHERE is before aggregation, so it filters out all rows (apparently). You want HAVING. But, fix the aliases, so they are not confusing:

SELECT ProductID, SUM(Quantity) AS total_Quantity
FROM Production.ProductInventory
GROUP BY ProductID
HAVING total_Quantity >= 1800;

Or, repeat the expression:

SELECT ProductID, SUM(Quantity) AS total_Quantity
FROM Production.ProductInventory
GROUP BY ProductID
HAVING SUM(Quantity) >= 1800;

2 Comments

@RyanWilson . . . As a point in fact, Lucasz had not (from what I could tell) adding the having portion of his answer when I first answered this. It is trickier to find edit histories for the first five minutes, but his answer continued to use WHERE.
@GordonLinoff If I missed that, then I apologize. I remove my down vote. Well, I tried to remove my down vote. No luck. I'll see if a moderator can help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.