简体   繁体   中英

Getting column ambiguously defined error in an SQL query

SELECT MAX(EMP.SAL),DEPT.DNAME
FROM EMP
JOIN DEPT
ON EMP.DEPTNO=DEPT.DEPTNO
GROUP BY DEPT.DNAME
ORDER BY DEPTNO ASC;

I was trying to print the max salary of the employees from emp table by grouping them by the name of the department which I reference from DEPT table as Department name is not defined in EMP table so I just wanted to print department name instead of department number (DEPTNO) which is defined in EMP table. I'm new with DBMS commands help me with this

You should not be getting an ambiguous column but an undefined column error.

If you want to order by the department number, you should include that in the GROUP BY :

SELECT MAX(EMP.SAL), DEPT.DNAME
FROM EMP JOIN
     DEPT
     ON EMP.DEPTNO = DEPT.DEPTNO
GROUP BY DEPT.DNAME, DEPT.DEPTNO
ORDER BY DEPTNO ASC;

This should be the same result -- assuming two different departments don't have the same name.

You can also use an aggregation function:

SELECT MAX(EMP.SAL), DEPT.DNAME
FROM EMP JOIN
     DEPT
     ON EMP.DEPTNO = DEPT.DEPTNO
GROUP BY DEPT.DNAME
ORDER BY MAX(DEPTNO) ASC;

The ORDER BY should only use expressions and columns that are available after the aggregation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM