SQL QUERY中的错误,用于分组依据

时间:2014-09-02 17:35:01

标签: sql oracle group-by

我想按部门编号和年龄选择平均工资,我使用了这个查询

SELECT 
    DEPARTMENT_NUMBER,
    ROUND((MONTHS_BETWEEN(SYSDATE, BIRTHDAY)) / 12) AS AGE,
    AVG(SALARY)
FROM 
    EMPLOYEE 
GROUP BY 
    DEPARTMENT_NUMBER, AGE;

但我收到错误:

  

ORA-00904:“年龄”:标识符无效

2 个答案:

答案 0 :(得分:5)

您无法在Oracle的group by中使用列别名。只需使用子查询:

SELECT DEPARTMENT_NUMBER, AGE, AVG(SALARY)
FROM (SELECT e.*, ROUND((MONTHS_BETWEEN(SYSDATE,BIRTHDAY))/12) AS AGE
      FROM EMPLOYEE
     ) e
GROUP BY DEPARTMENT_NUMBER, AGE;

答案 1 :(得分:4)

您无法按别名分组,请尝试以下操作:

    SELECT DEPARTMENT_NUMBER
           ,ROUND((MONTHS_BETWEEN(SYSDATE,BIRTHDAY))/12) AS AGE
           ,AVG(SALARY)
    FROM EMPLOYEE 
    GROUP BY DEPARTMENT_NUMBER, ROUND((MONTHS_BETWEEN(SYSDATE,BIRTHDAY))/12);