Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Referring to an aliased aggregate function in where?

Status
Not open for further replies.

SyntaxTerror

Technical User
Jan 5, 2011
52
US
If, in my select, I have something like
Code:
SUM(Quantity) as TotalQty
...Then how do I refer to that in the where clause?

I want to say...
Code:
WHERE TotalQty IS NOT NULL
...but it doesn't recognize the alias, so I try...
Code:
WHERE sum(Quantity) IS NOT NULL
...but it won't take that either.

Workarounds?
 
having sum(Quantity)>0

or
having isnull(sum(Quantity),0)>0
or
WHERE Quantity IS NOT NULL
 
Because it is an aggregate, you need to use a having clause.

Ex:

Code:
Select ItemNumber,
       Sum(Quantity) As TotalQty
From   SomeTable
Where  ShowSize > 7
Group By ItemNumber
Having Sum(Quantity) Is Not NULL


-George
Microsoft SQL Server MVP
My Blogs
SQLCop
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Oddly, when using HAVING, it's still producing null values...

Ah well. It's just a subquery. I'll filter out the NULLs when I reference it later.

Thanks all.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top