select
case location_id
when 1 then 'DELHI' when 2 then 'AHMEDABAD'
when 4 then 'HYDERABAD' when 5 then 'KOLKATA' when 6 then 'BANGALORE'
when 7 then 'MUMBAI' when 8 then 'CHENNAI'
end as CITY,
count(*) as Total
from #tmptab1
group by CITY
I get error
Msg 207, Level 16, State 1, Line 12
Invalid column name ‘CITY’
How to rectify this ? Please help.
You can’t use column aliases in
GROUP BYclauses. Please see Conceptual Order of Evaluation of a Select Statement, where you will see that the clauses are (logically) evaluated in this order:FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, UNION, ORDER BY.That is not exactly how the engine performs the operation, but it is a useful heuristic for a solid practical understanding of why you can’t use something from the
SELECTstatement in theGROUP BYclause — it isn’t logically available to theGROUP BYclause as it is evaluated later.There are several ways around this:
Repeat the entire expression in the
GROUP BYclause:Use a derived table:
Use a Common Table Expression (CTE), SQL Server 2005 and up:
Use CROSS APPLY, SQL Server 2005 and up:
Since your expression is deterministic, it is possible that you could simply do
GROUP BY location_id, however this is not the normal case, and you shouldn’t go around expecting to be able to circumvent normal aggregate grouping logic by selecting a single column, because most of the time such a CASE expression adds value that is not deterministic.In fact, because the information is not only deterministic but is about the real world (rather than the business rules) I would recommend that you NOT encode this information in your query! Create a
Locationtable and join to it. It is not best practice to put changeable user data directly into queries–queries are supposed to record process, not content, and what if you add a new location_id? All the queries that use it will have to change. Additionally, grouping bylocation_idwill not work properly if more than onelocation_idcan refer to the same city.