2012-01-31 50 views
0

好的,我主要處理相當簡單的SQL,事實上,我目前的問題似乎應該很簡單,但我一直沒有能夠提出正確的搜索條件來尋找解決方案。我以一對多的關係加入兩張桌子。我想按第二張表中的日期字段進行排序,同時按PK對結果進行分組。SQL加入訂單結果的日期和PK

MAIN 
-- 
MAINID, ACTION, DIVISION 
000001, HRREC, I 
000002, AUDIT, IV 
000003, TRAVEL, II 

SECONDARY 
-- 
MAINID, AUTHUSER, LOGINDATE, COMMENTS 
000002, Fred,  01/02/2012, Needs work 
000001, Smitty, 01/05/2012, making brisk progress 
000003, Fred,  03/10/2012, blah blah 
000002, Jimmy, 02/15/2011, something 
000001, Bill,  01/01/2012, neener neener 
000002, Saul,  12/13/2011, no action 

DESIRED OUTPUT 
-- 
MAINID, ACTION, DIVISION, AUTHUSER, LOGINDATE, COMMENTS 
000003, TRAVEL, II,  Fred,  03/10/2012, blah blah 
000001, HRREC, I,  Smitty, 01/05/2012, making brisk progress 
000001, HRREC, I,  Bill,  01/01/2012, neener neener 
000002, AUDIT, IV,  Fred,  01/02/2012, Needs work 
000002, AUDIT, IV,  Saul,  12/13/2011, no action 
000002, AUDIT, IV,  Jimmy, 02/15/2011, something 

The basic join I'd like to order 
-- 
SELECT MAIN.MAINID,MAIN.DIVISION,MAIN.ACTION,SECONDARY.AUTHUSER,SECONDARY.LOGINDATE,SECONDARY.COMMENTS 
FROM MAIN 
LEFT JOIN SECONDARY ON MAIN.MAINID=SECONDARY.MAINID; 

謝謝!

+0

不清楚你所說的「分組由PK結果」的意思;如果日期必須按MAINID推薦的每個MAINID組進行排序?也許MAINID按MAX(LOGINDATE)排序? – 2012-01-31 14:08:52

回答

1

如果您想通過LOGINDATE訂購內通過MAINID與MAX(LOGINDATE)排序組由組你sholud做到這一點:

SELECT 
    M.MAINID, 
    M.DIVISION, 
    M.ACTION, 
    S.AUTHUSER, 
    S.LOGINDATE, 
    S.COMMENTS 
FROM MAIN M LEFT OUTER JOIN (
     SELECT 
      MAINID, 
      MAX(LOGINDATE) MAXDATE 
     FROM SECONDARY 
     GROUP BY 
      MAINID 
    ) Q 
      ON M.MAINID=Q.MAINID 
     LEFT JOIN SECONDARY S 
      ON M.MAINID=S.MAINID 
ORDER BY 
    MAXDATE, LOGINDATE; 
+1

+1:雖然我會稍微改變它,因爲子查詢中不需要連接。 '主要LEFT JOIN次要LEFT JOIN(選擇mainid,MAX(logindate)從次要GROUP BY mainid)'... – MatBailie 2012-01-31 14:35:57

+0

你是對的。相應地編輯我的答案。 – 2012-01-31 14:54:19

+0

非常感謝,非常有幫助! – CBR 2012-01-31 18:19:51