Answer: Subquery with HAVING and Aggregate Functions
Explore how to write SQL queries using subqueries combined with HAVING clauses and aggregate functions like AVG and SUM. This lesson teaches you to filter grouped data effectively, join tables, and apply different techniques such as CTEs and derived tables to solve common interview challenges involving sales data analysis.
We'll cover the following...
Solution
The solution is given below:
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 ...