循环通过另一个表并使用值作为SELECT查询的变量

时间:2013-05-27 04:49:51

标签: sql-server loops

来自延迟表的样本数据如下所示:

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

请帮忙。

2 个答案:

答案 0 :(得分: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 Fiddle DEMO

答案 1 :(得分:0)

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

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