Use a calculated column in a where clause
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, note SUM()
is specified just once, using the results of the multiplication):
SELECT x.Code, x.AccountNumber, x.SalesFROM( SELECT p.Code, c.AccountNumber, SUM(p.UnitPrice *od.QtyShipped) AS Sales 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 GROUP BY p.Code, c.AccountNumber) AS xWHERE x.Sales > 100;
You can use the common table expression for this
;WITH CTE AS ( 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 GROUP BY p.Code, c.AccountNumber, Sale ) SELECT *FROM CTE WHERE CTE.Sales>100
If it's a calculated column you can use "HAVING".
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.ProductIdGROUP BY p.Code, c.AccountNumber, SalesHAVING SALES > 100;