Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

I'm trying to perform a group by action on an aliased column (example below) but can't determine the proper syntax.

SELECT       LastName + ', ' + FirstName AS 'FullName' FROM         customers GROUP BY     'FullName' 

What is the correct syntax?

Extending the question further (I had not expected the answers I had received) would the solution still apply for a CASEed aliased column?

SELECT            CASE         WHEN LastName IS NULL THEN FirstName         WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName     END AS 'FullName' FROM         customers GROUP BY          LastName, FirstName 

And the answer is yes it does still apply.

like image 983
Gavin Miller Avatar asked Jan 30 '09 21:01

Gavin Miller


People also ask

Can you GROUP BY an alias?

Aliases can be used only if they were introduced in the preceding step. So aliases in the SELECT clause can be used in the ORDER BY but not the GROUP BY clause. Reference: Microsoft T-SQL Documentation for further reading. Hope this helps.

Can GROUP BY use column alias?

Column aliases can be used with GROUP BY and ORDER BY clauses. We cannot use a column alias with WHERE and HAVING clauses.

Can you ORDER BY an alias in SQL?

Due to logical query processing order, alias can be used in order by.

How does GROUP BY work with multiple columns in SQL?

The SQL GROUP BY clause is used along with some aggregate functions to group columns that have the same values in different rows. The group by multiple columns technique is used to retrieve grouped column values from one or more tables of the database by considering more than one column as grouping criteria.


1 Answers

You pass the expression you want to group by rather than the alias

SELECT       LastName + ', ' + FirstName AS 'FullName' FROM         customers GROUP BY      LastName + ', ' + FirstName 
like image 87
cmsjr Avatar answered Sep 25 '22 21:09

cmsjr