Reputation: 45
I know that I cannot use an alias column inside of a WHERE clause, so I'm trying to figure out the best way to write my query, but am struggling. I tried "HAVING" to filter it, but then I can't use GROUP BY at the same time, which makes my Subtotal column sum all of the records in the entire DB.
Here's what I'm trying to do:
SELECT a.ID, SUM(b.Qty * b.Price) AS Subtotal
FROM tbl_One AS a
LEFT JOIN tbl_Two AS b ON b.TwoID = a.ID
WHERE Subtotal > 100 AND Subtotal < 200
GROUP BY a.ID
Any suggestions on how I could do this differently would be greatly appreciated!
Upvotes: 1
Views: 46
Reputation: 19635
You're right, you cannot call out your alias in the WHERE or HAVING clauses, but other than that I'm not sure what you mean; GROUP BY and HAVING are meant to be used together:
SELECT a.ID, sum(b.Qty*b.Price) AS Subtotal
FROM tbl_One AS a
LEFT JOIN tbl_Two AS b ON b.TwoID = a.ID
GROUP BY a.ID
HAVING sum(b.Qty*b.Price) > 100 AND sum(b.Qty*b.Price) < 200
Upvotes: 2