SQL - using alias in Group By

前端 未结 10 1641
不思量自难忘°
不思量自难忘° 2020-11-22 08:52

Just curious about SQL syntax. So if I have

SELECT 
 itemName as ItemName,
 substring(itemName, 1,1) as FirstLetter,
 Count(itemName)
FROM table1
GROUP BY it         


        
相关标签:
10条回答
  • 2020-11-22 09:35

    Some DBMSs will let you use an alias instead of having to repeat the entire expression.
    Teradata is one such example.

    I avoid ordinal position notation as recommended by Bill for reasons documented in this SO question.

    The easy and robust alternative is to always repeat the expression in the GROUP BY clause.
    DRY does NOT apply to SQL.

    0 讨论(0)
  • 2020-11-22 09:40

    SQL is implemented as if a query was executed in the following order:

    1. FROM clause
    2. WHERE clause
    3. GROUP BY clause
    4. HAVING clause
    5. SELECT clause
    6. ORDER BY clause

    For most relational database systems, this order explains which names (columns or aliases) are valid because they must have been introduced in a previous step.

    So in Oracle and SQL Server, you cannot use a term in the GROUP BY clause that you define in the SELECT clause because the GROUP BY is executed before the SELECT clause.

    There are exceptions though: MySQL and Postgres seem to have additional smartness that allows it.

    0 讨论(0)
  • 2020-11-22 09:43

    SQL Server doesn't allow you to reference the alias in the GROUP BY clause because of the logical order of processing. The GROUP BY clause is processed before the SELECT clause, so the alias is not known when the GROUP BY clause is evaluated. This also explains why you can use the alias in the ORDER BY clause.

    Here is one source for information on the SQL Server logical processing phases.

    0 讨论(0)
  • 2020-11-22 09:44

    Beware of using aliases when grouping the results from a view in SQLite. You will get unexpected results if the alias name is the same as the column name of any underlying tables (to the views.)

    0 讨论(0)
  • 2020-11-22 09:46

    In at least Postgres, you can use the alias name in the group by clause:

    SELECT itemName as ItemName1, substring(itemName, 1,1) as FirstLetter, Count(itemName) FROM table1 GROUP BY ItemName1, FirstLetter;

    I wouldn't recommend renaming an alias as a change in capitalization, that causes confusion.

    0 讨论(0)
  • 2020-11-22 09:49

    I'm not answering why it is so, but only wanted to show a way around that limitation in SQL Server by using CROSS APPLY to create the alias. You then use it in the GROUP BY clause, like so:

    SELECT 
     itemName as ItemName,
     FirstLetter,
     Count(itemName)
    FROM table1
    CROSS APPLY (SELECT substring(itemName, 1,1) as FirstLetter) Alias
    GROUP BY itemName, FirstLetter
    
    0 讨论(0)
提交回复
热议问题