31. Top Categories by Average Price
Beginner Mode
Objective
Write an SQL query to find the top 3 product categories with the highest average price. For each of these categories, return the number of active products, the average price rounded to two decimal places, and the count of products with low stock (less than 10 units).
Additional information
- Only consider active products (
is_active = true). - If multiple categories have the same average price, order them by the number of active products in descending order.
- Return the results ordered by average price in descending order first, then by product count in descending order.
- The results should be limited to the top 3 categories.
- The
productstable contains information about the products. - The
inventorytable contains information about the stock levels of the products.
Constraints:
- You can assume that
productsandinventorytables are non-empty. - Each product in the
productstable has a corresponding entry in theinventorytable.
Clarifications:
avg_priceshould be the average price of the active products in each category.product_countshould be the count of active products in each category.low_stock_itemsshould be the count of active products with a stock level less than 10 in each category.
Examples
Example 1:
Output:
Input:
| inventory | |
|---|---|
| product_id | stock_level |
| 1 | 5 |
| 2 | 15 |
| 3 | 8 |
| 4 | 25 |
| 5 | 12 |
| 6 | 6 |
| 7 | 0 |
| 8 | 18 |
| products | ||||
|---|---|---|---|---|
| category | id | is_active | name | price |
| Electronics | 1 | true | Gaming Laptop | 1299.99 |
| Electronics | 2 | true | Smartphone | 899.99 |
| Fashion | 3 | true | Designer Handbag | 799.99 |
| Sports | 4 | true | Running Shoes | 129.99 |
| Sports | 5 | true | Hiking Boots | 159.99 |
| Fashion | 6 | true | Leather Wallet | 89.99 |
| Electronics | 7 | false | Tablet | 599.99 |
| Electronics | 8 | true | Smart Watch | 299.99 |
| avg_price | category | low_stock_items | product_count |
|---|---|---|---|
| 833.32 | Electronics | 1 | 3 |
| 444.99 | Fashion | 2 | 2 |
| 144.99 | Sports | 0 | 2 |
Code Environment
Sign in or try as guest to run your code.
Essential
SQL 0/33
Spark 0/20
Snowflake 0/22
Python 0/24
Need more practice in this area? Explore more questions →
Samsung
Revolut
Accenture
Adobe
Google
LinkedIn
Datadog
Wix
Dropbox
Meta
OpenAI
Hulu
Uber
X
DoorDash
Anthropic
Amazon
ActivisionBlizzard
Vercel
Crypto.Com
Zscaler
DeutscheBank
Apple
GoDaddy
GitLab
BMW
PayPal
Snowflake
AMD
Twilio
Atlassian
JPMorgan
NVIDIA
IBM
Databricks
Coinbase
Cisco
Robinhood
Twitter
Microsoft
Palantir
Netflix
VMware
Cloudflare
Stripe
Lyft
Salesforce
GitHub
Bloomberg
Airbnb
Walmart
SAP
HashiCorp
Instacart
Mastercard
Intel
Visa
Tesla