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

后端 未结 12 1664
慢半拍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

    You can use CROSS APPLY to create an alias and use it in the GROUP BY clause, like so:

    SELECT       FullName
    FROM         Customers
    CROSS APPLY  (SELECT LastName + ', ' + FirstName AS FullName) Alias
    GROUP BY     FullName
    
    0 讨论(0)
  • 2020-11-29 01:09

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

    SELECT       LastName + ', ' + FirstName AS 'FullName'
    FROM         customers
    GROUP BY      LastName + ', ' + FirstName
    
    0 讨论(0)
  • 2020-11-29 01:16

    If you want to avoid the mess of the case statement being in your query twice, you may want to place it in a User-Defined-Function.

    Sorry, but SQL Server would not render the dataset before the Group By clause so the column alias is not available. You could use it in the Order By.

    0 讨论(0)
  • Unfortunately you can't reference your alias in the GROUP BY statement, you'll have to write the logic again, amazing as that seems.

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

    Alternately you could put the select into a subselect or common table expression, after which you could group on the column name (no longer an alias.)

    0 讨论(0)
  • 2020-11-29 01:20

    Given your edited problem description, I'd suggest using COALESCE() instead of that unwieldy CASE expression:

    SELECT FullName
    FROM (
      SELECT COALESCE(LastName+', '+FirstName, FirstName) AS FullName
      FROM customers
    ) c
    GROUP BY FullName;
    
    0 讨论(0)
  • 2020-11-29 01:25

    This is what I do.

    SELECT FullName
    FROM
    (
      SELECT LastName + ', ' + FirstName AS FullName
      FROM customers
    ) as sub
    GROUP BY FullName
    

    This technique applies in a straightforward way to your "edit" scenario:

    SELECT FullName
    FROM
    (
      SELECT
         CASE
           WHEN LastName IS NULL THEN FirstName
           WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
         END AS FullName
      FROM customers
    ) as sub
    GROUP BY FullName
    
    0 讨论(0)
提交回复
热议问题