1

延迟表中的示例数据如下所示:

+----------+-------------+
| 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 个查询)遍历该表。

请帮忙。

4

2 回答 2

1

你有没有尝试过类似的东西

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 小提琴演示

于 2013-05-27T04:55:04.557 回答
0

使用UNION运算符。它合并任意数量的给定表的行

这是文档: http ://dev.mysql.com/doc/refman/5.0/en/union.html

于 2013-05-27T04:54:03.583 回答