繁体   English   中英

在两个连接的表中选择与最大值对应的列

[英]select a column corresponding to max value in two joined tables

我有两个表,比如说用户和采访。 一个用户可以有多个采访记录。

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

还有其他选择,有些是标准的,有些是特定于数据库的。

在获取面试时重写以使用 OUTER APPLY,这样您就可以使用 order by 而不是 MAX

select u.UserID, firstname, lastname, LatestInterviewDetails.ID, LatestInterviewDetails.DateOfInterview as latestDOI 
from users u 
OUTER APPLY (SELECT TOP 1 Id, DateOfInterview
    FROM interviews
    WHERE interviews.UserID = u.UserId
    ORDER BY interviews.DateOfInterview DESC
) as LatestInterviewDetails

注意:前提是您使用的是 Microsoft SQL Server

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM