从连接中选择最新日期

时间:2014-06-03 09:30:20

标签: sql sql-server tsql

我在加入时遇到问题。我正在获取重复记录。请帮我解决..

这是我的疑问:

select requestinstanceid from
 requestidt [RIM] 
 inner join requestcdt [RCDT] on [RIM].requestinstanceid = [RCDT].requestinstanceid     
 left join requestcmt [RCMT] on [RCDT].requestcommentid = [RCMT].requestcommentid   
 inner join requestddt [RDDT] on [RDDT].requestinstanceid = [RIM].requestinstanceid   
 left join requestdmt [RDMT] on [RDMT].requestdocumentid = [RDDT].requestdocumentid

我得到的结果如下:

requestinstanceid
184
184
386
389
389
397

我不应该得到重复记录,我想从每条记录中获取最新日期。

1 个答案:

答案 0 :(得分:1)

此代码连接到派生表的“前1”。您应该能够弄清楚如何应用它来加入按日期DESC排序的子查询的前1位。

SELECT T2.TempEmailID, T1.EmailID
FROM tbl1 T1
LEFT JOIN (SELECT *, RANK() Over (Partition By EmailID Order By TempEmailID DESC) as TopOne FROM tbl2) T2 ON T1.EmailID = T2.EmailID AND TopOne = 1