Help with MySQL and CASE WHEN with a range of values

Posted by kickdaddy on Stack Overflow See other posts from Stack Overflow or by kickdaddy
Published on 2010-05-26T13:07:08Z Indexed on 2010/05/26 13:11 UTC
Read the original article Hit count: 165

Filed under:
|
|

I have an accounts table and a records table where accounts have multiple records. I would like to break down the account totals by "count of records" range. i.e. show the breakdown of

Count of Records | Count

0-25 | 100 25 - 50 | 122 50 - 100 | 300

etc.

I am using the following query, but I can't get it to group by "grp" which is what I want, any help on the best way to modify query? Thanks!

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

© Stack Overflow or respective owner

Related posts about mysql

Related posts about case