Search code examples
sqlsql-servert-sqlsyntax

How do I perform a GROUP BY on an aliased column in 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.


Solution

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

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