I'm trying to use a calculated column in a where clause.
I've been trying everything from CROSS APPLY, to sub-query select but it does not give me anything near what I need.
My query so far:
SELECT p.Code, c.AccountNumber, Sales = (SUM(p.UnitPrice) * SUM(od.QtyShipped)) FROM [dbo].Customer c
LEFT JOIN [dbo].OrderHeader oh ON oh.CustomerId = c.Id
LEFT JOIN [dbo].OrderDetail od ON od.OrderHeaderId = oh.Id
LEFT JOIN [dbo].Product p ON p.Id = od.ProductId
WHERE Sales > 100
GROUP BY p.Code, c.AccountNumber, Sales
This does not work, as 'Sales' is an invalid column
3条答案
按热度按时间mzillmmw1#
Using Derived Columns in a predicate
You'll need to wrap the inner query in a derived table or CTE in order to be able to use derived columns in the
WHERE
clause (Also, noteSUM()
is specified just once, using the results of the multiplication):Repeating the Derived Column in a HAVING clause
As per @Jonny's comment, the other way is not to DRY up the calculated column, but to instead repeat the calculation. Use
HAVING
instead ofWHERE
after aGROUP BY
has been applied.In either case, as per comments below, note that the calculated expression is
SUM(p.UnitPrice * od.QtyShipped)
and notSUM(p.UnitPrice) * SUM(od.QtyShipped)
.xxslljrj2#
You can use the common table expression for this
e4yzc0pl3#
If it's a calculated column you can use "HAVING".