延迟表中的示例数据如下所示:
+----------+-------------+
| Customer | DaysDelayed |
+----------+-------------+
| 698125 | 13 |
| 698126 | 31 |
| 698127 | 2 |
| 698128 | 11 |
| 698129 | 5 |
| 698130 | 4 |
| 698131 | 42 |
| 698132 | 29 |
| 698133 | 29 |
+----------+-------------+
所需的输出是:
+------------+-------+
| Range | Count |
+------------+-------+
| 0-7 days | 3 |
| 8-20 days | 2 |
| 21-30 days | 2 |
| 31-45 days | 2 |
+------------+-------+
为了获得输出,我编写了 4 个查询:
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
依此类推(标签的值和 WHERE 条件在每个查询中都会发生变化)。
日期范围不时变化,范围的数量也可以增加/减少。
从可维护性的角度来看,我想将 Range 值存储在一个表中,如下所示:
+---------+------------+----------+----------+
| 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 |
+---------+------------+----------+----------+
并使用一个 SELECT 查询(而不是目前的 4 个查询)遍历该表。
请帮忙。