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

Alias in Group By clause - invalid identifier

我尝试了很多方法,但我无法解决这个问题...

我正在执行 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;

ERROR at line 4: ORA-00904: "AGE": invalid identifier

有什么想法吗?

不要在您的群组中使用别名:

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;

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.

正确的做法:

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;