查询按范围限制对记录进行分组

时间:2013-01-11 07:54:28

标签: mysql sql select group-by

我有一张如下表。

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条记录。

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

输出

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

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

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

2 个答案:

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

答案 1 :(得分: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 |