...
/Answer: Subquery with HAVING and Aggregate Functions
Answer: Subquery with HAVING and Aggregate Functions
Find a detailed explanation of using subqueries with the HAVING clause and AVG() function.
We'll cover the following...
Solution
The solution is given below:
-- The query to find employees whose average sales is more than the average sales for the categorySELECT E.EName AS 'Employee Name', AVG(S.SalesAmount) AS 'Average Sales'FROM Employees AS EJOIN Sales S ON E.EID = S.EIDGROUP BY E.EName, S.CategoryIDHAVING AVG(S.SalesAmount) > (SELECT AVG(SalesAmount)FROM Sales AS S2WHERE S2.CategoryID = S.CategoryID);
Code explanation
The explanation of the solution code is given below:
Line 2: The
SELECT
statement selects the columnsEName
andAverage Sales
. TheAverage Sales
column calculates the average of theSalesAmount
using the aggregate window function. We useAS
to set an alias for the columns and tables.Line 3: The data is retrieved from the
Employees
table.Line 4: The
JOIN
is performed betweenEmployees
andSales
.Line 5: The
GROUP BY
specifies theEName
andCategoryID
columns to group the data.Lines 6–9: The
HAVING
clause filters the groups to keep only those that match a specific condition.Line 6: The
>
operator checks if the averageSalesAmount
is higher than the averageSalesAmount
of the same category.Lines 7–9: The subquery calculates the average of
SalesAmount
using theAVG()
function. The data is retrieved from the ...