2013-02-21 73 views
0

好太多結果,這裏的select語句左外Select查詢連接返回從主表

SELECT dbo.tbl_inspectors.user_firstname, 
     dbo.tbl_inspectors.user_lastname, 
     dbo.tbl_inspectors.user_loc, 
     dbo.tbl_appraisals.appPartA, 
     dbo.tbl_appraisals.appPartB, 
     dbo.tbl_appraisals.appAppraised, 
     dbo.tbl_appraisals.appFinalized, 
     dbo.tbl_appraisals.appDate, 
     dbo.tbl_inspectors.appProcStart, 
     dbo.tbl_inspectors.appDue, 
     dbo.tbl_inspectors.inspAdhocStaff, 
     dbo.tbl_inspectors.access_id, 
     dbo.tbl_appraisals.appraiseID, dbo.tbl_inspectors.user_id 
FROM dbo.tbl_inspectors 
     LEFT OUTER JOIN 
     dbo.tbl_appraisals ON dbo.tbl_inspectors.user_id = bo.tbl_appraisals.inspectID 

如果有反對的tbl_appraisals表tbl_inspectors.user_id多個結果,然後我得到了多個結果每個檢查員,我只是想要它從tbl_appraisals對tbl_inspectors user_id拉最近的比賽,我怎麼能做到這一點?

PS tbl_appraisals.appDate是確定從tbl_appraisals

+1

確定最近一行的列是什麼? – 2013-02-21 09:52:26

+0

tbl_appraisals.appDate – 2013-02-21 10:05:49

回答

1

假設引擎的最近結果字段不MySQL的

這是一個「每組TOP 1」的問題

SELECT 
    * 
FROM 
    (
    SELECT I.user_firstname, 
      I.user_lastname, 
      I.user_loc, 
      A.appPartA, 
      A.appPartB, 
      A.appAppraised, 
      A.appFinalized, 
      A.appDate, 
      I.appProcStart, 
      I.appDue, 
      I.inspAdhocStaff, 
      I.access_id, 
      A.appraiseID, 
      I.USER_ID, 
      ROW_NUMBER() OVER (PARTITION BY I.user_id ORDER BY COALESCE(A.appDate, '19000101') DESC) AS rn 
    FROM dbo.tbl_inspectors I 
      LEFT OUTER JOIN 
      dbo.tbl_appraisals A ON I.user_id = A.inspectID 
    ) X 
WHERE 
    X.rn = 1 
+0

引擎是MS-SQL,返回錯誤: Msg 102,Level 15,State 1,Line 13 '。'附近的語法錯誤。 – 2013-02-21 10:20:30

+0

修復了缺少逗號。在你的問題中也是這樣...在SELECT子句中的appDate後 – gbn 2013-02-21 10:25:12

+0

好的,謝謝gbn,在一個側面說明我達到了我的極限,我有限的知識,我理解基礎知識,但想更好地理解加入,子查詢和更高級的功能,你能推薦任何好的教程資源或閱讀材料嗎?,再次感謝m8 – 2013-02-21 10:28:27