Question: Histogram
Explore how to write an SQL query that categorizes products into defined price ranges. Learn to count products within those ranges and order the output by lower price bounds, enhancing your skills in grouping and conditional aggregation.
We'll cover the following...
Question
Given the following structure of the Products table:
Field | Type |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Where, ProductID is the primary key and CategoryID is the foreign key referencing the Categories table. The table contains information about products available in the store.
You are analyzing product pricing using the Products table, which includes:
Price: It is the price of each product.
Write an SQL query that returns a histogram of product prices by grouping them into the following ranges:
0–50
51–100
101–500
501–1000
1001+
Your output should display each Price Range along with the number of products (Product Count) in that range. The results should be ordered by the lower bound of each range.
Expected output
The expected output is shown below:
Price Range | Product Count |
0–50 | 17 |
51–100 | 4 |
101–500 | 3 |
501–1000 | 1 |
1001+ | 1 |
Try it yourself
You can write a query in the following playground:
Hints
Below are some hints to help you understand these concepts better: