Search code examples
sqljoindb2subquery

How to display the current info base on date


My SQL script is to display the company, employee number, last name, first name, current job, and current salary.

To arrive at the current something implies there are dates involved.

How do I display the current job and salary of that employee?

emp (base table)

empno lastname firstname
111 james lebron
222 bryant kobe
333 jordan michael
444 curry stephen

dept_job view

company empno effdate job salary
lakers 111 04/16/15 assistant 1500.00
lakers 111 02/02/16 coach 4000.00
lakers 222 07/22/17 analyst 3000.00
bulls 333 04/12/17 secretary 5000.00
bulls 333 07/28/18 manager 5000.00
warriors 444 10/04/19 chef 2000.00

I used MAX() on the effectivity date (effdate) to get the most current job and salary. But it displays past job and salary.

SELECT z.company, em.empno, em.lastname, em.firstname, z.job, z.salary
FROM emp em
JOIN ( SELECT dj.company, dj.empno, dj.effdate, dj.job, dj.salary
    FROM dept_job dj
    JOIN (SELECT company, empno, MAX(effdate) AS maxefffdate
        FROM dept_job
        GROUP BY company, empno) pe
    ON dj.empno = pc.empno AND dj.effdate = pe.maxeffdate) z
ON em.empno = z.empno
ORDER BY company, empno;

Result (wrong)

company empno lastname firstname job salary
lakers 111 james lebron assistant 1500.00
lakers 111 james lebron coach 4000.00
lakers 222 bryant kobe analyst 3000.00
bulls 333 jordan michael secretary 5000.00
bulls 333 jordan michael manager 5000.00
warriors 444 curry stephen chef 2000.00

What I want

company empno lastname firstname job salary
lakers 111 james lebron coach 4000.00
lakers 222 bryant kobe analyst 3000.00
bulls 333 jordan michael manager 5000.00
warriors 444 curry stephen chef 2000.00

Solution

  • SELECT dj.company
        ,em.empno
        ,em.lastname
        ,em.firstname
        ,dj.job
        ,dj.salary
    FROM emp em
    JOIN dept_job dj ON em.empno = dj.empno
    JOIN (
        SELECT empno
            ,MAX(effdate) AS maxefffdate
        FROM dept_job
        GROUP BY empno
        ) z
    ON dj.empno = z.empno
        AND dj.effdate = z.maxefffdate
    ORDER BY company
        ,empno;