SQL JOIN每个都有最新的行

时间:2015-04-21 12:59:56

标签: sql join

我有这些表格:

document

id, docnumber, uploaded_at
...
2, 2014567, '2014-05-30'
3, 9518488, '2014-06-02'

document_history

document_id, date, status
2, '2014-06-15', 3
3, '2014-06-12', 3
2, '2014-06-10', 2

我需要得到这样的东西:

document.id, document.docnumber, document_history.date, document_history.status
2, 2014567, '2014-06-15', 3
3, 9518488, '2014-06-12', 3

每个文档只需要一行。

2 个答案:

答案 0 :(得分:1)

如果您要查找最近的document_history日期,则可以使用子查询返回最大日期,然后将其连接到自身以返回该日期的状态。

SELECT
    d.id, 
    d.docnumber,
    dh.MaxDate AS Date,
    dh2.status
FROM @Document d
JOIN (SELECT Id, MAX(date) AS MaxDate 
        FROM @DocumentHistory
        GROUP BY Id) AS dh
    ON dh.id = d.id
JOIN @DocumentHistory AS dh2
    ON dh2.id = dh.id
    AND dh2.date = dh.MaxDate

答案 1 :(得分:0)

写为:

;with cte as
( select D.id,
         D.docnumber,
         DH.date,
         DH.status,
         row_number() over (partition by D.id order by DH.date desc) as rownum 
   from Document D
   join document_history DH on D.id = DH.document_id
 )
 select id,docnumber,date,status from CTE
 where rownum = 1

DEMO