Answer: Nested Subquery with HAVING and Aggregate Functions
Explore how to write SQL queries using nested subqueries combined with HAVING clauses and aggregate functions. This lesson helps you understand grouping data, filtering groups based on aggregates, and applying joins. You will also learn alternate methods like CTEs and window functions to solve similar problems.
Solution
The solution is given below:
Code explanation
The explanation of the solution code is given below:
Lines 2–4: The
SELECTstatement selects the columnsCategory Name, and the total amount of sales made using the aggregate function with theSalesAmountcolumn. We useASto set an alias for the columns and tables.Line 5: The data is retrieved from the
ProductCategoriestable.Line 6: The
JOINis performed betweenProductCategoriesandSales.Line 7: The
GROUP BYspecifies theCategoryIDandMonthcolumns to group the data.Lines 8–13: The
HAVINGclause filters the groups to keep only records with the maximum total sales for each category. The subquery calculates the ...