1

我有一个员工表和一个具有一对多关系的 leave_allocation 表,每个员工在一段时间内都有许多休假分配。我想获得每位员工的最新分配。

我尝试了查询,但日期和天数与同一行不相关

select e.employee_number, e.nme, MAX(l.date), l.days 
from employee e, leave_allocation l 
where l.employee_id = e.employee_id
group by e.employee_number, e.nme

如何获得每位员工的最新分配?

4

3 回答 3

2
SELECT e.employee_number
      ,e.nme
      ,l.days
  FROM employee e
      , leave_allocation l
      ,(SELECT employee_id
              ,MAX(DATE) date
          FROM leave_allocation
         GROUP BY employee_id) m
 WHERE l.employee_id = e.employee_id
   AND l.employee_id = m.employee_id
   AND l.date = m.date

如果可以有多行具有相同的employee_number 和日期,那么您需要求和。

SELECT e.employee_number
      ,e.nme
      ,sum(l.days)
  FROM employee e
      , leave_allocation l
      ,(SELECT employee_id
              ,MAX(DATE) date
          FROM leave_allocation
         GROUP BY employee_id) m
 WHERE l.employee_id = e.employee_id
   AND l.employee_id = m.employee_id
   AND l.date = m.date
GROUP BY e.employee_number
        ,e.nme
于 2012-08-30T16:45:57.180 回答
1

MAX()日期放在子查询中:

SELECT e.employee_number, e.nme, l.leavedate, la.days
FROM employee e
INNER JOIN
(
   SELECT Max(date) leavedate, employee_id
   FROM leave_allocation
   GROUP BY employee_id
) l
   ON e.employee_id = l.employee_id
INNER JOIN leave_allocation la
   ON l.employee_id = la.employee_id
   AND l.leavedate = la.date

我还将查询切换为使用 ANSI 连接语法而不是表之间的逗号。

于 2012-08-30T16:48:07.597 回答
1

试试这个,

SELECT  e.employee_number, e.nme, c.maxDate, l.days 
FROM    employee e 
            INNER JOIN leave_allocation l
                ON l.employee_id = e.employee_id
            INNER JOIN
            (
                select employee_id, MAX(date) maxDate
                from    leave_allocation  
                group by employee_id
            ) c ON c.employee_id = l.employee_ID AND
                    c.maxDate = l.date
于 2012-08-30T16:48:50.053 回答