SQL Group by Age Range

Group by age_c -- age_range isn't a physical column. More specifically, do this:

group by case
   when age_c <18 then 'Under 18'
   when age_c between 18 and 24 then '18-24'
   when age_c between 25 and 34then '25-34'
 END

Since age_range is an aliased column, the group by is not aware of it at all. Grouping happens before the column set is calculated. The only clause that you can use your aliases in is order by, since that's the only clause that's executed after the column set is calculated.


Try it this way instead:

 SELECT SUM(CASE WHEN age_c < 18 THEN 1 ELSE 0 END) AS [Under 18],
        SUM(CASE WHEN age_c BETWEEN 18 AND 24 THEN 1 ELSE 0 END) AS [18-24],
        SUM(CASE WHEN age_c BETWEEN 25 AND 34 THEN 1 ELSE 0 END) AS [25-34]
 FROM contacts