0

我有一个如下表。

CREATE TABLE budgets(limit_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
                     upper_limit INT, 
                     lower_limit INT);

表中数值如下

INSERT INTO budgets(lower_limit, upper_limit)
             VALUES(0, 15000),
                   (10200, 15300),
                   (15200, 17002),
                   (30000, 45050),
                   (17002, 30000),
                   (27002, 30500),
                   (30500, 35200),
                   (45200, 55000),
                   (55000, 65020),
                   (25000, 30000),
                   (40000, 60000),
                   (65000, 75000);

我使用如下选择查询来获取值

SELECT 'Betw 0 to 25000', COUNT(limit_id)
  FROM budgets
 WHERE lower_limit>=0  AND  upper_limit<=25000
 UNION ALL
SELECT 'Betw 25000 to 50000', COUNT(limit_id)
  FROM budgets
 WHERE lower_limit>=25000  AND  upper_limit<=50000
 UNION ALL
 SELECT 'Betw 50000 to 75000',COUNT(limit_id)
   FROM budgets
  WHERE lower_limit >=50000  AND  upper_limit<=75000

我希望所有行都在上述限制范围内负责。

我在表中有 12 条记录。

我希望所有记录都属于任何一个范围类别。但是通过运行查询,在某些条件下我只得到 9 行。

输出是

Between 0 to 25000          3
Between 25000 to 50000      4
Between 50000 to 75000      2 

其余 3 条记录不属于任何范围。

帮助我知道我是否在数据库设计中犯了错误,或者我为上述要求编写了错误的查询

4

2 回答 2

1

这将起作用

 SELECT 'Betw 0 to 25000', COUNT(limit_id)
  FROM budgets
 WHERE upper_limit>=0  and upper_limit<=25000  
 UNION ALL
SELECT 'Betw 25000 to 50000', COUNT(limit_id)
  FROM budgets
 WHERE upper_limit>=25000  and upper_limit<=50000   
 UNION ALL
SELECT 'Betw 50000 to 75000',COUNT(limit_id)
  FROM budgets
 WHERE upper_limit>=50000  and upper_limit<=75000   

输出将是

Between 0 to 25000          3
Between 25000 to 50000      5
Between 50000 to 75000      4
于 2013-01-11T10:06:04.660 回答
0

尝试这个:

编辑

SELECT IFNULL(CONCAT('Between ', lowerLimit, ' to ',upperLimit), 'Not in Range') bType, COUNT(limit_id) budgetCount 
FROM budgets b 
LEFT JOIN (SELECT 0 lowerLimit, 25000 upperLimit 
           UNION 
           SELECT 25000 lowerLimit, 50000 upperLimit 
           UNION 
           SELECT 50000 lowerLimit, 75000 upperLimit
          ) A ON b.upper_limit >= A.lowerLimit AND b.lower_limit <= A.upperLimit
GROUP BY bType;


SELECT CONCAT('Between ', lowerLimit, ' to ',upperLimit) bType, COUNT(limit_id) budgetCount 
FROM budgets b 
INNER JOIN (SELECT 0 lowerLimit, 25000 upperLimit 
            UNION 
            SELECT 25000 lowerLimit, 50000 upperLimit 
            UNION 
            SELECT 50000 lowerLimit, 75000 upperLimit
          ) A ON b.upper_limit >= A.lowerLimit  AND b.lower_limit <= A.upperLimit
GROUP BY bType;

检查此链接SQL FIDDLE DEMO

输出

|                  BTYPE | BUDGETCOUNT |
----------------------------------------
|     Between 0 to 25000 |           3 |
| Between 25000 to 50000 |           4 |
| Between 50000 to 75000 |           2 |
于 2013-01-11T08:50:02.003 回答