Search code examples
left-joinsap-ase

List Staff Names with Their Current Job/Department (Table Staff LEFT JOIN Table Department_Staff)


I have these tables and data..

staff
(id, name, current_department_id)
1, "John", 1 
2, "Matt", 1

department 
(id, name)
1, "Sales"
2, "Support"

designation 
(id, name)
1, "Sales Exac"
2, "Sales Manager"
3, "Support Exec"

department_staff
(department_id, staff_id, start_year, end_year, designation_id)
1, 1, 2005, 2006, 1
1, 1, 2007, 2008, 2
2, 2, 2007, 2008, 3

Now, I want to list all staff with their current designation/department.

I use this syntax

SELECT Name=s.name, 
                     Department=d.name,
                     JSTART=ds.start_year, JEND=ds.end_year,
                     Designation=j.name FROM
             staff s
                     LEFT JOIN department d ON d.id = s.current_department_id 
                     LEFT JOIN department_staff ds ON ds.staff_id = s.id 
                     LEFT JOIN designation j ON j.id = ds.designation_id

But the result shows all John's work history. I just want the latest job for John and everybody else. This statement produced the same result as above

SELECT Name=s.name, 
                         Department=d.name,
                         JSTART=ds.start_year, JEND=ds.end_year,
                         Designation=j.name FROM

FROM department_staff ds
LEFT JOIN department d ON d.id = ds.department_id
LEFT JOIN staff s ON s.id = ds.staff_id
LEFT JOIN designation ON j.id = ds.designation_id

//Side note: After writing to this point, it seems that I do not need to store current_department_id in table staff because I can get that in table department_staff.

I repeat my question: How do I list my staff with their latest job designation and department?

Thank you for your time.


Solution

  • try:

    SELECT  b.name "Name",
        c.name "Department",
        start_year "JSTART",
        end_year "JEND",
        d.name "Designation"
    FROM    dep_staff a,
        staff b,
        dep c,
        desig d
    WHERE   start_year =
                    (
                        SELECT  MAX(start_year)
                        FROM    dep_staff e
                        WHERE   a.staff_id=e.staff_id
                        AND     start_year < end_year
                    )
    AND     start_year < end_year
    AND     a.dep_id = c.id
    AND     a.staff_id = b.id
    AND     a.desig_id = d.id