我有两个表,分别是“用户”和“采访”。一个用户可以有多个采访记录。
Users
-----
UserID
FirstName
LastName
Interviews
----------
InterviewID
UserID
DateOfInterview
我只想获取最新的采访记录。这是我的查询
select u.UserID, firstname, lastname, max(DateOfInterview) as latestDOI
from users u
left join interviews i
on u.UserID = i.UserID
GROUP BY u.UserID, firstname, lastname
ORDER BY max(DateOfInterview) DESC
如何更新查询以也返回InterviewID(即对应于max(DateOfInterview)的查询)?
您可以在WHERE
子句中使用聚合子查询,而不是在选择列表中使用聚合函数:
select u.UserID, firstname, lastname, i.InterviewId, DateOfInterview as latestDOI
from users u
left join interviews i
on u.UserID = i.UserID
where i.UserId is null or i.DateOfInterview = (
select max(DateOfInterview)
from interviews i2
where i2.UserId = u.UserId
)
那确实假设max(DateOfInterview)
每个用户都是唯一的,但是这个问题没有明确的答案。请注意,主查询不再是聚合查询,因此此类查询的约束不适用。
还有其他方法可以解决该问题,值得研究一下,因为诸如此类的相关子查询可能会影响性能。例如,您可以使用内联视图生成每个用户的最新采访日期的表,并使用该视图的联接将用户与其最新采访的ID连接起来:
select u.*, im.latestDOI, i2.InterviewId
from
users u
left join (
select UserID, max(DateOfInterview) as latestDOI
from interviews i
group by UserID
) im
on u.UserId = im.UserId
left join interviews i2
on im.UserId = i2.UserId and im.latestDOI = i2.DateOfInterview
也有其他选择,一些标准和其他特定于DB的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句