Group By子句中的别名-无效的标识符

时间:2018-11-20 22:13:38

标签: sql oracle having

我通过许多方法尝试了很多次,但是我无法解决这个问题...

我正在执行Oracle SQL查询:

SELECT
    TRUNC(months_between(sysdate, DateofBirth) / 12) AS "age"
FROM players
group by age
HAVING COUNT 
    (TRUNC(months_between(sysdate, DateofBirth) / 12)) > 30;
  

第4行出现错误:   ORA-00904:“ AGE”:无效的标识符

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

不要通过以下方式在您的群组中添加别名:

SELECT
    TRUNC(months_between(sysdate, DateofBirth) / 12) AS "age"
FROM players
group by
    TRUNC(months_between(sysdate, DateofBirth) / 12)
HAVING
    COUNT(TRUNC(months_between(sysdate, DateofBirth) / 12)) > 30;

答案 1 :(得分:2)

  

在Oracle和SQL Server中,不能在GROUP BY中使用术语   您在SELECT子句中定义的子句,因为GROUP BY是   在SELECT子句之前执行。

https://stackoverflow.com/a/3841804/6358346

正确的方法:

SELECT TRUNC(months_between(sysdate, DateofBirth) / 12) AS "age"
FROM players
GROUP BY TRUNC(months_between(sysdate, DateofBirth) / 12)
HAVING COUNT(TRUNC(months_between(sysdate, DateofBirth) / 12)) > 30;