Reputation: 743
Sample data from the Delays Table is shown below:
+----------+-------------+
| Customer | DaysDelayed |
+----------+-------------+
| 698125 | 13 |
| 698126 | 31 |
| 698127 | 2 |
| 698128 | 11 |
| 698129 | 5 |
| 698130 | 4 |
| 698131 | 42 |
| 698132 | 29 |
| 698133 | 29 |
+----------+-------------+
The output desired is:
+------------+-------+
| Range | Count |
+------------+-------+
| 0-7 days | 3 |
| 8-20 days | 2 |
| 21-30 days | 2 |
| 31-45 days | 2 |
+------------+-------+
For getting the output I have written 4 queries:
SELECT '0-7 days', Count(*)
FROM Delays
WHERE DaysDelayed between 0 AND 7
SELECT '8-20 days', Count(*)
FROM Delays
WHERE DaysDelayed between 8 AND 20
and so on (the values for the label and the WHERE condition changing in each query).
The day ranges change from time to time and also the number of ranges can increase/decrease.
From a maintainability perspective, I want to store the Range values in a table as follows:
+---------+------------+----------+----------+
| RangeID | RangeName | LowerEnd | UpperEnd |
+---------+------------+----------+----------+
| 1 | 0-7 days | 0 | 7 |
| 2 | 8-20 days | 8 | 20 |
| 3 | 21-30 days | 21 | 30 |
| 4 | 31-45 days | 31 | 45 |
+---------+------------+----------+----------+
and loop through this table with one SELECT query (instead of 4 queries at present).
Please help.
Upvotes: 1
Views: 479
Reputation: 166356
Have you tried something like
SELECT RangeName,
COUNT(d.Customer) Cnt
FROM Ranges r LEFT JOIN
Delays d ON d.DaysDelayed BETWEEN r.LowerEnd AND r.UpperEnd
GROUP BY RangeName
Upvotes: 1
Reputation: 1806
Use UNION
operator. It merges rows of any number of given tables
Here is the documentation: http://dev.mysql.com/doc/refman/5.0/en/union.html
Upvotes: 0