1

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.

2 Answers 2

1

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

SQL Fiddle DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.