cjones3724 cjones3724 - 1 year ago 99
MySQL Question

SQL Group by multiple value groups in one column

So I have a table with a column that I need to group by certain categories within that column. For example there is 20 codes in the column that goes in one group called Residential and 30 codes that go in Commercial. Is this possible? How would I create groups made out of multiple different values in the same columns?

Answer Source

You could use a case expression:

SELECT  code_group, COUNT(*)
FROM    (SELECT CASE WHEN code IN ('code1', 'code2', 'etc') THEN 'Residential'
                     WHEN code IN ('code3', 'code4') THEN 'Commercial'
                     ELSE NULL
                END AS code_group
         FROM . . .) t
GROUP BY code_group
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download