从已连接的表中删除重复记录并保留最后一个出现记录?

时间:2014-08-08 05:33:11

标签: sql-server

我有两张桌子,一张桌子有一些记录。表B有一些修改日期,表A的插入日期。现在我必须加入两个表并获得前3条记录,没有重复。

**Table A** 
id  name 
1   Arul
2   siva
3   raja
4   sanju

**Table B**
Id modifed TabId(Refered Table A) Modified Date
1  inserted    1                  2014-08-08 10:46:42.250
2  updated     1                  2014-08-08 10:46:42.624
3  inserted    2                  2014-08-08 10:46:42.724
4  inserted    3                  2014-08-08 10:46:43.624
5  inserted    4                  2014-08-08 10:46:44.624
6  updated     4                  2014-08-08 10:47:42.624
7  updated     4                  2014-08-08 10:48:42.624
8  updated     3                  2014-08-08 10:49:42.624   

2 个答案:

答案 0 :(得分:0)

试试这个

 Select distinct top 3 a.*,Modified Date from tablea a 
inner join tableb b on (a.Id=b.TabId) 
order by Modified Datedesc;

Sql Fiddle

答案 1 :(得分:0)

SELECT  *
FROM    (SELECT a.Id, a.Name,b.ModifiedDate,
                ROW_NUMBER() OVER (PARTITION BY a.Id ORDER BY b.ModifiedDate) AS RowNumber
         from tableA a, tableB b where a.id  = b.TabId ) AS temp
WHERE   temp.RowNumber = 1