SQL 2005, I have a table with a column 'ages_c', I need to group the records by age ranges. This is the query that I found on this site and it's getting me 90% there but the 'group by' is erroring, Invalid column name 'age_range'
select
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 as age_range,
Count(*) as count
from contacts
group by age_range
order by age_range
When I group and order by 'age_c' my result is:
Under 18 1
18-24 1
18-24 1
25-34 1
What I want is:
Under 18 1
18-24 2
25-34 1
Thanks.
7条答案
按热度按时间acruukt91#
Try it this way instead:
vmdwslir2#
Group by
age_c
-- age_range isn't a physical column. More specifically, do this:Since
age_range
is an aliased column, thegroup 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 isorder by
, since that's the only clause that's executed after the column set is calculated.ryhaxcpt3#
You can't group by a column you create in the query. You'll have to do it like this:
or GROUP BY
s1ag04yj4#
If your database supports FILTER WHERE syntax then this can be archived in a very elegant way:
Or this one if not:
c9x0cxw05#
Is that your actual code you're using? It doesn't look like it because you're missing a space between 34 and then. That code would error in SQL. Mind sharing the actual unmodified query?
Anyways, you can use a temp table or a nested query.
Don't forget to drop the temporary table when you're done with it
wqsoz72f6#
vngu2lb87#
We can't perform Group By operation directly by alias column. So I tried here by using CTE. It worked well.
Image shows the code and its output