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.
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.
Column aliases can be used with GROUP BY and ORDER BY clauses. We cannot use a column alias with WHERE and HAVING clauses.
Due to logical query processing order, alias can be used in order by.
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.
You pass the expression you want to group by rather than the alias
SELECT LastName + ', ' + FirstName AS 'FullName' FROM customers GROUP BY LastName + ', ' + FirstName
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With