Answer: Using RANK()
Explore how to apply the RANK() window function in SQL to rank product categories based on sales data. Understand the use of joins, grouping, and ordering to compute rankings and learn alternative ranking methods like DENSE_RANK() and ROW_NUMBER(). This lesson helps you master ranking functions critical for intermediate SQL interviews.
Solution
The solution is given below:
Code explanation
The explanation of the solution code is given below:
Lines 2–4: The
SELECTstatement selects the columnsCategoryNameandTotalSales. TheRANK()function assigns a rank to each category based onTotalSalesin descending order. We useASto set an alias for the calculated column.Line 5: The
FROMclause specifies the table name asProductCategories.Line 6: The
JOINis applied to theProductstable on theCategoryIDcolumns in theProductCategoriesandProductstables.Line 7: The
JOINis applied withSalesonCategoryIDcolumns in theProductsandSalestables.Line 8: The
GROUP BYclause groups the results byCategoryName.Line 9: The
ORDER BYclause sorts the results by theTotalSalescolumn in descending order.
Recalling relevant concepts
We have covered the following concepts in this question:
Selective columns ...