SQL连接按日期和PK排序结果

时间:2012-01-31 14:03:47

标签: sql

好吧,我主要处理的是相当简单的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;

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您想通过LOGINATE在由MAINID制作的组中按照MAX(LOGINDATE)排序的组进行排序,请执行以下操作:

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;