← All SQL interview questions

Top two revenue positions per category

MediumWindow FunctionsAmazonWalmart

A category head wants the top two products by total revenue in every category. If two products tie, they share the same position and the next position is not skipped, so a tie can return more than two rows for a category.

From product_sales, return category, product_name, total_revenue and rnk for products ranked 1 or 2 within their category. Order by category, rnk, then product_name.

Sample data

Table: product_sales

17 row(s) · showing first 8

sale_idINTproduct_nameTEXTcategoryTEXTrevenueNUMERIC(10,2)
1EarbudsElectronics12000.00
2EarbudsElectronics8000.00
3SmartwatchElectronics15000.00
4SmartwatchElectronics5000.00
5Power BankElectronics9000.00
6WebcamElectronics4000.00
7WebcamElectronics2500.00
8Air FryerHome18000.00