MySQL和CASE WHEN具有一系列值

时间:2010-05-26 13:07:08

标签: mysql case

我有一个帐户表和一个帐户有多条记录的记录表。我想按“记录数”范围细分帐户总数。即显示

的细分
Count of Records | Count
=========================
0-25 | 100
25 - 50 | 122
50 - 100 | 300

我正在使用以下查询,但我无法通过“grp”将其分组,这是我想要的,有关修改查询的最佳方法的任何帮助吗?

SELECT count(*) as ct,
    CASE 
        WHEN COUNT(*) < 25 THEN '1-25'
        WHEN COUNT(*) >= 25 < 50 THEN '25-50'
        WHEN COUNT(*) >= 50 < 100 THEN '50-100'
        WHEN COUNT(*) >= 100 < 250 THEN '100-250'
        WHEN COUNT(*) >= 250 < 500 THEN '250-500'
        WHEN COUNT(*) >= 500 < 1000 THEN '500-1000'
        ELSE '1000+'
    END AS grp
    FROM records r,accounts a
    WHERE r.account_id=a.id
    ORDER BY ct

2 个答案:

答案 0 :(得分:20)

试试这个:

SELECT count(*) as ct, 
CASE  
    WHEN COUNT(*) < 25 THEN '1-25' 
    WHEN COUNT(*) >= 25 < 50 THEN '25-50' 
    WHEN COUNT(*) >= 50 < 100 THEN '50-100' 
    WHEN COUNT(*) >= 100 < 250 THEN '100-250' 
    WHEN COUNT(*) >= 250 < 500 THEN '250-500' 
    WHEN COUNT(*) >= 500 < 1000 THEN '500-1000' 
    ELSE '1000+' 
END AS grp 
FROM records r, accounts a 
WHERE r.account_id=a.id 
GROUP BY r.account_id, a.id, 
    CASE  
    WHEN COUNT(*) < 25 THEN '1-25' 
    WHEN COUNT(*) >= 25 < 50 THEN '25-50' 
    WHEN COUNT(*) >= 50 < 100 THEN '50-100' 
    WHEN COUNT(*) >= 100 < 250 THEN '100-250' 
    WHEN COUNT(*) >= 250 < 500 THEN '250-500' 
    WHEN COUNT(*) >= 500 < 1000 THEN '500-1000' 
    ELSE '1000+' END
ORDER BY count(*)

您必须“定义”您希望将原始数据行聚合到的“桶”...这就是Group By子句的用途......它定义了基表中每一行的标准分析以确定它的数据将聚合到哪个“桶”... group by子句中定义的表达式或表达式是这些桶的“定义”。

当查询处理原始数据行时,此表达式的值与现有存储桶相同的任何行都会聚合到该存储桶中...任何未表示值的新行通过现有存储桶导致创建新存储桶...

答案 1 :(得分:7)

您需要一个子查询。如果这是一个视图,那么你需要使用两个视图。

SELECT s.ct, s.grp FROM ( 
SELECT count(*) as ct,
    CASE 
        WHEN COUNT(*) < 25 THEN '1-25'
        WHEN COUNT(*) >= 25 AND COUNT(*) < 50 THEN '25-50'
        WHEN COUNT(*) >= 50 AND COUNT(*) < 100 THEN '50-100'
        WHEN COUNT(*) >= 100 AND COUNT(*) < 250 THEN '100-250'
        WHEN COUNT(*) >= 250 AND COUNT(*) < 500 THEN '250-500'
        WHEN COUNT(*) >= 500 AND COUNT(*) < 1000 THEN '500-1000'
        ELSE '1000+'
    END AS grp
    FROM records r,accounts a
    WHERE r.account_id=a.id) as s

Group BY s.grp;