0

My(Scott) goal is to get manager's name ,salary and deptno using correlated subquery. As below, I could get expected result, but similar subquery has been used several times. Is there a another neat way(without repeated similar pattern as below)?

SELECT
    O.ENAME EMP_NAME
    ,(SELECT DISTINCT FIRST_VALUE(I.ENAME) OVER (PARTITION BY NULL ORDER BY I.SAL DESC)
        FROM SCOTT.EMP I
        WHERE I.EMPNO=O.MGR  --correlated to outer
     ) AS MGR_NAME
     ,(SELECT DISTINCT FIRST_VALUE(I.SAL) OVER (PARTITION BY NULL ORDER BY I.SAL DESC)
        FROM SCOTT.EMP I
        WHERE I.EMPNO=O.MGR  --correlated to outer
     ) AS MGR_SAL
     ,(SELECT DISTINCT FIRST_VALUE(I.DEPTNO) OVER (PARTITION BY NULL ORDER BY I.SAL DESC)
        FROM SCOTT.EMP I
        WHERE I.EMPNO=O.MGR  --correlated to outer
     ) AS MGR_DEPTNO
    from SCOTT.EMP O;
1
  • 1
    Simple outer join to the emp table to get the managers record. Each employee has at most one manager, so performing FIRST_VALUE analytic function with a DISTINCT seems to be a bit of overkill. Commented Sep 2, 2020 at 15:10

1 Answer 1

2
select  e.ename emp_name, m.ename mgr_name, m.sal mgr_sal, m.deptno mgr_deptno
from    emp e left join emp m
on      e.mgr = m.empno
order   by m.deptno, e.ename;

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.