0

我有这些表格和数据..

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

现在,我想列出所有员工的当前职务/部门。

我使用这种语法

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

但结果显示了约翰的所有工作历史。我只想要约翰和其他人的最新工作。该语句产生与上述相同的结果

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

//旁注:写到这里之后,似乎我不需要将current_department_id存储在表staff中,因为我可以在表department_staff中得到它。

我重复我的问题:我如何列出我的员工及其最新的工作名称和部门?

感谢您的时间。

4

1 回答 1

0

尝试:

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
于 2013-08-22T10:56:25.057 回答