SQL - using alias in Group By

前端 未结 10 1802
不思量自难忘°
不思量自难忘° 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: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.

提交回复
热议问题