November 15, 2006 at 3:05 pm
Hi;
the following query fails for me in SQL Server 8:
SELECT SUM(c1), c2 as t FROM foo GROUP BY t
Server: Msg 207, Level 16, State 3, Line 1
Invalid column name 't'.
If I change the query to group by c2, it succeeds:
SELECT SUM(c1), c2 as t FROM foo GROUP BY c2
My question is, is this ANSI-SQL compliant behavior? Or a shortcoming in SQL Server 2000? The same query fails in Oracle with a similar error message, and then succeeds when the column name is used in the GROUP BY instead of the alias. I've googled GROUP BY syntax, but found nothing on using aliases, so have to conclude that it's not allowed, but am curious why - it may be useful if you want to group by an expression - is there a reason why this would be hard to implement ?
Thanks
November 15, 2006 at 3:42 pm
Russians use to get stuck with this kind of questions after 2nd bottle of vodka.
What you've got today?
Yes, this is it, and this behavior is ANSI compliant.
And this gives you a hint that you need to think about db design and data structure when you create tables, not when you need to build a report.
_____________
Code for TallyGenerator
November 15, 2006 at 4:19 pm
The issue is that a lot of the stuff happens BEFORE the select occurs. WHERE, GROUP, HAVING all occur on the whole data table before the select. So the alias in the select doesn't exist yet.
In layperson's terms....
SELECT C1, C2
FROM mytable
WHERE C1 = 3
GROUP BY C1, C2
First it takes all the data in mytable and finds the rows where C1 = 3. Then it groups it by C1, C2. Then from those rows it selects C1 and C2 only.
-SQLBill
November 15, 2006 at 5:42 pm
I see. That makes sense. A colleague gave me a query that had a case expression (see below), and thinking about it further, it doesn't really make sense to group by a constant so these types of queries are just wrong.
Thanks for the help
SELECT SUM(x),
case when name LIKE 'Z%' then 'NA' else name end as cust
FROM foo
GROUP BY cust
November 15, 2006 at 5:57 pm
It's clear example of hardcoded business logic.
Wrong by definition.
This is the core of your problem, not ANSI standad or its implementation in MS SQL.
_____________
Code for TallyGenerator
November 15, 2006 at 8:55 pm
But you could do this:
SELECT SUM(x),
case when name LIKE 'Z%' then 'NA' else name end as cust
FROM foo
GROUP BY case when name LIKE 'Z%' then 'NA' else name end
November 16, 2006 at 8:26 am
How about:
SELECT SUM(x),cust
from
(
SELECT x,case when name LIKE 'Z%' then 'NA' else name end as cust
FROM foo
) t
GROUP BY cust
November 16, 2006 at 10:38 am
Using a derived table should also work.
November 16, 2006 at 11:11 am
Cool, thanks for all the above suggestions
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply