Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Group By Column Alias

Author  Topic 

icanpee4hours
Starting Member

4 Posts

Posted - 2010-09-09 : 09:42:32
Hello there!
Is there any way to use a column alias in a GROUP BY clause?
The column that I want to GROUP BY is calculated for every row in a SELECT subquery inside brackets. SELECT (SELECT .... ) AS ColumnAlias.

CSears
Starting Member

39 Posts

Posted - 2010-09-09 : 10:08:31
Is it safe to assume that you are referencing information in the outer select from the inner select statement. If that is the case you will likely need to include those references in the group by clause.

SELECT A.Value1, (SELECT B.Value1 FROM TableB B WHERE B.Value2 = A.Value2), SUM(A.Value3) ColumnAlias FROM TableA A GROUP BY A.Value1
-- this will fail because A.Value2 is located in the select statement and is not contained within an aggregate or the
-- group by clause

SELECT A.Value1, (SELECT B.Value1 FROM TableB B WHERE B.Value2 = A.Value2), SUM(A.Value3) ColumnAlias FROM TableA A GROUP BY A.Value1, A.Value2
-- this will work but may give you different results than you were looking for since you ere trying to group by the
-- result of the nested select statement


If you are trying to get the select statement to group by the results of that nested select statement, you may need to write the statement so as to remove the nested select in favor of a case statement, or by making a join.
Go to Top of Page

icanpee4hours
Starting Member

4 Posts

Posted - 2010-09-09 : 10:25:23
Thanks Again CSears.
Indeed it gives me different results. Actually It doesn't group by A.Value1
Gee, is that so hard to group by a single column?? How do I get rows distincted by a single column without changing the statement?
Go to Top of Page
   

- Advertisement -