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

问题描述 投票:2回答:2

这个问题在这里已有答案:

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

我正在执行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”:标识符无效

有任何想法吗?

sql oracle having
2个回答
2
投票

在Oracle和SQL Server中,不能在SELECT子句中定义的GROUP BY子句中使用术语,因为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;

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;
© www.soinside.com 2019 - 2024. All rights reserved.