要将您的分配限制为每个资源的最新分配,您需要找到每个 resource_id 的最晚开始日期并INNER JOIN
返回分配表;
SELECT assignment.*
FROM assignment
INNER JOIN
( SELECT assignment.resource_id,
MAX(assignment.StartDate) AS StartDate
FROM assignment
GROUP BY assignment.resource_id
) MaxAssignment
ON assignment.resource_id = MaxAssignment.resource_id
AND assignment.StartDate = MaxAssignment.StartDate;
由于您只想LEFT JOIN
这样做,因此您需要将上述全部内容移入子查询,LEFT JOIN
并将整个子查询移回主查询:
SELECT resource.firstname,
resource.lastname,
resource.fte,
project.name as project_name,
role.name as role_name,
assignment.startdate,
assignment.enddate,
assignment.numberofdaysperweek
FROM resource
LEFT JOIN
( SELECT assignment.*
FROM assignment
INNER JOIN
( SELECT assignment.resource_id,
MAX(assignment.StartDate) AS StartDate
FROM assignment
GROUP BY assignment.resource_id
) MaxAssignment
ON assignment.resource_id = MaxAssignment.resource_id
AND assignment.StartDate = MaxAssignment.StartDate
) assignment
ON resource.id = assignment.resource_id
AND assignment.enddate < now()
LEFT JOIN project
ON project.id = assignment.project_id
LEFT JOIN role
ON role.id = assignment.role_id;
如果我误解了您对每个资源的“最后”分配的解释,您可能需要修改子查询内的聚合门MaxAssignmen
和返回的内部连接assignments
,但应该适用相同的原则。
编辑
出于某种原因,我认为这是 MySQL,但下面评论中的错误消息看起来更像 Postgresql,在这种情况下,您可以使用ROW_NUMBER
将其限制为每个资源的最后一个分配:
SELECT resource.firstname,
resource.lastname,
resource.fte,
project.name as project_name,
role.name as role_name,
assignment.startdate,
assignment.enddate,
assignment.numberofdaysperweek
FROM resource
LEFT JOIN
( SELECT *, ROW_NUMBER() OVER(PARTITION BY ResourceID ORDER BY StartDate DESC) RN
FROM assignment
) assignment
ON resource.id = assignment.resource_id
AND RN = 1
AND assignment.enddate < now()
LEFT JOIN project
ON project.id = assignment.project_id
LEFT JOIN role
ON role.id = assignment.role_id;