我想找到完成所有相关任务的所有未完成的请求。在这些请求中找到最新完成的任务用户电子邮件。也就是说,我需要返回RequestID,TaskID,UpdatedDate,email
这是我的疑问:
select r.RequestID,r.UpdatedDate,u.Email
from Request r
left outer join Task t1 on r.RequestID = t1.RequestID
left outer join Task t2 on r.RequestID = t2.RequestID and t2.UpdatedDate > t1.UpdatedDate
left outer join Users u on t1.AssignedEmp = u.UserID
where r.RequestStatusID in (2,6) and t1.TaskStatusID in (2,5)
and t2.RequestID is null
此查询为我提供了每个请求的最新完成或取消任务,但同一请求中还有其他任务尚未完成。例如这些记录:
RequestID = 1
TaskID = 1, TaskStatusID = 2 (completed) UpdatedDate = '20150417'
TaskID = 2, TaskStatusID = 3 (InProgress)UpdatedDate = '20150416'
将选择此请求。但我不想要它。我想要所有TaskStatusID =已完成或已取消
我该如何解决?谢谢!
答案 0 :(得分:0)
尝试使用相关的not exists
子查询来过滤掉至少有一个未完成任务的请求。使用apply获取最近更新任务的电子邮件。
select
r.RequestID,
r.UpdatedDate,
u.Email
from Request as r
cross apply (
select top (1) u.Email
from Task as t
inner join Users as u
on t.AssignedEmp = u.UserID
where t.RequestID = r.RequestID
order by r.UpdatedDate desc
) as u /* the user associated with the most recently updated task */
where not exists (
select *
from Task as t
where t.RequestID = r.RequestID
and t.TaskStatusID <> 2
) /* a not completed task does not exist */
and r.RequestStatusID <> 2 /* the request is not completed */
答案 1 :(得分:0)
您可以在ranking function (ROW_NUMBER)
CTE
;WITH C AS(
SELECT ROW_NUMBER() OVER (ORDER BY t.RequestID, t.UpdatedDate DESC) AS Rn
,r.RequestID
,t.TaskID
,r.UpdatedDate
,u.Email
FROM Request AS r
LEFT JOIN Task AS t ON t.RequestId = r.RequestId
LEFT JOIN Users AS u ON u.UserId = t.AssignedEmp
WHERE r.RequestStatusID IN (2,6)
AND t.TaskStatusID IN(2, 5)
)
SELECT RequestID, TaskID, UpdatedDate, Email
FROM C
WHERE Rn = 1
答案 2 :(得分:0)
最后我解决了这个问题...
select r.RequestID,
t.UpdatedOn, u.FirstName + ' ' + u.LastName as UserName, u.Email
from Request r
join
(
select RequestID,AssignedEmp, TaskID, Row_Number() OVER (Partition By RequestID Order By UpdatedDate desc) AS RowNo , UpdatedDate, TaskStatusID
from Task
where RequestID not in ( select t1.RequestID
from Task t1
where t1.TaskStatusID not in (2,5)
group by t1.RequestID, t1.TaskID
)
) t
on r.RequestID = t.RequestID and t.RowNo = 1
and r.RequestStatusID in (2,6)
join Users u on t.AssignedEmp = u.UserID
order by r.RequestID desc