Hi friends the above question asked by one of CMM 5 level company.Using row_number we will find the each department wise maximum salary.
Query : SELECT E.ENAME,D.DNAME,E.DEPTNO,E.SAL FROM(
SELECT E.ENAME,E.SAL,E.DEPTNO,ROW_NUMBER() OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) RN
FROM EMP E) E INNER JOIN DEPT D ON E.DEPTNO=D.DEPTNO
WHERE RN=1;
The same approach using DENSE_RANK()
Query : SELECT E.ENAME,D.DNAME,E.SAL,E.DEPTNO FROM(
SELECT E.ENAME,E.SAL,E.DEPTNO,DENSE_RANK() OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) DR
FROM EMP E) E INNER JOIN DEPT D ON E.DEPTNO=D.DEPTNO WHERE DR=1;
Using rank()
Query : SELECT E.ENAME,D.DNAME,E.SAL,E.DEPTNO FROM(
SELECT E.ENAME,E.SAL,E.DEPTNO,RANK() OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) RN FROM EMP E)
E INNER JOIN DEPT D ON E.DEPTNO=D.DEPTNO WHERE RAN=1
Using rank()
Query : SELECT E.ENAME,D.DNAME,E.SAL,E.DEPTNO FROM(
SELECT E.ENAME,E.SAL,E.DEPTNO,RANK() OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) RN FROM EMP E)
E INNER JOIN DEPT D ON E.DEPTNO=D.DEPTNO WHERE RAN=1
Please comments here if you know any other methods regarding this topic.
Thanks for giving exact query
ReplyDeletesql query to find department having maximum employees
Use below query
ReplyDeleteSELECT SALARY FROM
(SELECT A.ID,A.NAME,A.SALARY
FROM EMP A
UNION ALL
SELECT B.ID,B.NAME,B.SALARY
FROM DEPT B) C
QUALIFY ROW_NUMBER() OVER (ORDER BY SALARY DESC)=1