...
/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
SELECTstatement selects the columnsENameandAverage Sales. TheAverage Salescolumn calculates the average of theSalesAmountusing the aggregate window function. We useASto set an alias for the columns and tables.Line 3: The data is retrieved from the
Employeestable.Line 4: The
JOINis performed betweenEmployeesandSales.Line 5: The
GROUP BYspecifies theENameandCategoryIDcolumns to group the data.Lines 6–9: The
HAVINGclause filters the groups to keep only those that match a specific condition.Line 6: The
>operator checks if the averageSalesAmountis higher than the averageSalesAmountof the same category.Lines 7–9: The subquery calculates the average of
SalesAmountusing theAVG()function. The data is retrieved from the ...