SQL查询多个表/记录

时间:2011-10-23 19:55:19

标签: sql

我必须创建一个查询,为多个表中的每个玩家(用户)编译一堆数据。例如,我有两个表: tblMembers Off_Ice_Testing

每个tblMembers(或没有)有多个off_ice_testing。如何选择一个具有最新日期的off_ice_testing?

我试过了:

   SELECT m.LastName, 
          m.FirstName, 
          office.Date AS [off ice date]
   FROM tblMembers AS m 
   LEFT JOIN (SELECT Date, UserID
              FROM Off_Ice_Testing) AS office ON m.UserID = office.UserID
   WHERE m.LastName LIKE '%player%'

但是,这会为每个 Off_ice_Testing 取回记录。如果我在派生表中执行 Top(1),那将无效。我觉得我应该知道这一点,但我被困住了。为了将来参考,您会将这种类型的查询称为什么?

1 个答案:

答案 0 :(得分:1)

SELECT m.LastName, m.FirstName, o.[Date] AS [off ice date]
FROM tblMembers AS m
LEFT JOIN 
(
  SELECT UserID, MAX([Date]) as [Date] FROM Off_Ice_Testing
  GROUP BY UserID
)o ON (o.UserID = m.UserID)
WHERE     (m.LastName LIKE '%player%')