2011-10-23 134 views
0

我必須創建一個查詢,爲多個表中的每個玩家(用戶)編譯一堆數據。例如,我有兩個表格:tblMembersOff_Ice_Testing多個表/記錄的SQL查詢

每個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的記錄。如果我在派生表中執行頂部(1),那不起作用。我覺得我應該知道這一點,但我卡住了。而爲了將來的參考,你會稱這種類型的查詢?

+0

您正在使用哪種SQL(Oracle或MSSQL)? –

回答

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%') 
+0

+1:較少涉及到ROW_NUMBER :) –

+0

啊,當然是MAX(日期)。但是,我意識到,您還需要派生表的Group By UserID(至少對於MSSQL)。謝謝! – scojomodena

+0

哎呀..是的,我忘了它:)修復 – a1ex07