I’m trying to find a way to group prices in a database table by price “group”.
So my database table looks something like this:
+-------+------------------+
| Field | Type |
+-------+------------------+
| id | int(11) unsigned |
| name | varchar(255) |
| price | varchar(30) |
+-------+------------------+
Those are the relevant fields in my database table.
What I’m trying to accomplish is to run a query that will group results by price range, so items that fall between $1 and $10 would go into group #1; $11 to $20 would go into price group #2, etc… so it should look like this:
+-------------+------------+
| price_group | item_count |
+-------------+------------+
| $1-$10 | 10 |
+-------------+------------+
| $11-$20 | 8 |
+-------------+------------+
| $21-$30 | 22 |
+-------------+------------+
| $31-$40 | 58 |
+-------------+------------+
| $41-$40 | 3 |
+-------------+------------+
I don’t have any code that I’ve tried because I’m not really sure where to begin on this. Still searching trying to find a clue.
You can group by the price (offset by 1 because of where you put your group divisions), divided by ten, cast to an integer. Consider the group $21-$30. If you subtract one, that will be $20-$29. Divide by ten (and cast to integer), anything in that group will return $2, giving you a constant for the price group.
Also note that I did
SUM(item_count)to get the total for that group.The
price_groupreturned here will just be the tens digit. For example, for group “$21-$30”,price_groupreturned will be “2”.