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

后端 未结 12 1848
慢半拍i
慢半拍i 2020-11-29 00:20

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

SELECT       LastName + \', \'         


        
12条回答
  •  甜味超标
    2020-11-29 01:07

    Sorry, this is not possible with MS SQL Server (possible though with PostgreSQL):

    select lastname + ', ' + firstname as fullname
    from person
    group by fullname
    

    Otherwise just use this:

    select x.fullname
    from 
    (
        select lastname + ', ' + firstname as fullname
        from person
    ) as x
    group by x.fullname
    

    Or this:

    select lastname + ', ' + firstname as fullname
    from person
    group by lastname, firstname  -- no need to put the ', '
    

    The above query is faster, groups the fields first, then compute those fields.

    The following query is slower (it tries to compute first the select expression, then it groups the records based on that computation).

    select lastname + ', ' + firstname as fullname
    from person
    group by lastname + ', ' + firstname
    

提交回复
热议问题