2020年5月23日 星期六

GROUP BY無法使用alias column name

原因
https://stackoverflow.com/questions/3841295/sql-using-alias-in-group-by

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.

問題描述:
SELECT country AS c, YEAR(hiredate) AS yearhired, COUNT(*) AS numemployees
FROM HR.Employees
WHERE hiredate >= '20140101'
GROUP BY country, YEAR(hiredate)
-- GROUP BY country, yearhired -- 無效的資料行名稱 'yearhired'。
HAVING COUNT(*) > 1
ORDER BY country, yearhired DESC;
--ORDER BY c, yearhired DESC; --可以執行

沒有留言:

張貼留言