cjones3724 cjones3724 - 3 months ago 10
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

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