SELECT SUM(SubTotal)/17 AS AverageSales
FROM Sales.SalesOrderHeader
WHERE SalesPersonID IS NOT NULL
-- 4734570.8343
That query gave me the result for the average amount of sales for each salesperson.
SELECT SalesPersonID
, SUM(SubTotal) AS TotalSalesBySalesPerson
, FirstName + ' ' + LastName AS [Sales Person]
FROM Sales.SalesOrderHeader
JOIN Person.Person
ON SalesOrderHeader.SalesPersonID = Person.BusinessEntityID
WHERE SalesPersonID IS NOT NULL
GROUP BY SalesPersonID, FirstName, LastName
HAVING SUM(SubTotal) < 4734570
ORDER BY TotalSalesBySalesPerson DESC
This query gives me the exact results I'm looking for but I want to replace the '4734570' value with an actual statement. My guess was 'HAVING SUM(SubTotal) < SUM(SubTotal)/17' but that doesn't seem to work.
Can anyone help with this?
SELECT SalesPersonID
, SUM(SubTotal) AS TotalSalesBySalesPerson
, FirstName + ' ' + LastName AS [Sales Person]
FROM Sales.SalesOrderHeader
JOIN Person.Person
ON SalesOrderHeader.SalesPersonID = Person.BusinessEntityID
WHERE SalesPersonID IS NOT NULL
GROUP BY SalesPersonID, FirstName, LastName
HAVING SUM(SubTotal) < SUM(SubTotal)/17
ORDER BY TotalSalesBySalesPerson DESC
This is what I tried. It returned an empty table.
If you queries are correct, you can just replace the value with a subquery to get the result:
Also, you mentioned you were calculating an average... there is an
AVG()function you may want to use instead ofSUM()/17, but since I don't know your business rules I will leave it to you to explore.