Answer: Using RANK()
Find a detailed explanation of using RANK() in SQL.
Solution
The solution is given below:
-- The query to rank the records using RANK()SELECT PC.CategoryName,SUM(S.SalesAmount) AS TotalSales,RANK() OVER (ORDER BY SUM(S.SalesAmount) DESC) AS 'Rank'FROM ProductCategories AS PCJOIN Products AS P ON PC.CategoryID = P.CategoryIDJOIN Sales AS S ON P.CategoryID = S.CategoryIDGROUP BY PC.CategoryNameORDER BY TotalSales DESC;
Code explanation
The explanation of the solution code is given below:
Lines 2–4: The
SELECT
statement selects the columnsCategoryName
andTotalSales
. TheRANK()
function assigns a rank to each category based onTotalSales
in descending order. We useAS
to set an alias for the calculated column.Line 5: The
FROM
clause specifies the table name asProductCategories
.Line 6: The
JOIN
is applied to theProducts
table on theCategoryID
columns in theProductCategories
andProducts
tables.Line 7: The
JOIN
is applied withSales
onCategoryID
columns in theProducts
andSales
tables.Line 8: The
GROUP BY
clause groups the results byCategoryName
.Line 9: The
ORDER BY
clause sorts the results by theTotalSales
column in descending order.
Recalling relevant concepts
We have covered the following concepts in this question:
Selective columns ...