...
/Answer: Nested Subquery with HAVING and Aggregate Functions
Answer: Nested Subquery with HAVING and Aggregate Functions
Find a detailed explanation of using nested subqueries with the HAVING clause and aggregate functions.
Solution
The solution is given below:
-- Query to find months with maximum total sales for each categorySELECT PC.CategoryName AS 'Category Name',S.Month AS Month,SUM(S.SalesAmount) AS 'Total Sales'FROM ProductCategories AS PCJOIN Sales S ON PC.CategoryID = S.CategoryIDGROUP BY PC.CategoryID, S.MonthHAVING SUM(S.SalesAmount) = (SELECT MAX(TotalSales)FROM (SELECT CategoryID, Month, SUM(SalesAmount) AS TotalSalesFROM Sales GROUP BY CategoryID, Month )AS MonthlyTotalsWHERE MonthlyTotals.CategoryID = PC.CategoryID);
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 maximum total sales for each category and month by grouping the sales data.Lines 8–13: The
HAVINGclause filters the groups to keep only those that match a specific condition.Line 8: The
=operator keeps the records where the sum ofSalesAmountfor each group ...