从表中的重复记录中获取最新ID

时间:2011-09-16 06:25:01

标签: sql

所以我有两个表,一个是RAWtable,另一个是MAINtable,我必须得到最新的groupID 存在多个记录(比较相同的名称,代码)。例如,我在RAWtable上有这个:

id  groupid     name        code
1   G09161405   Name1       Code1
2   G09161406   Name1       Code1

这两个记录应该被视为一个,并且只应返回此值:

id  groupid     name        code
2   G09161406   Name1       Code1

此行是shiuld在主表中插入的唯一行。提供了返回最新的GroupID(groupid是日期和时间的组合)

我试过这个但是没有用:

SELECT MAST.ID, MAST.code, MAST.name FROM RAWtable AS MAST INNER JOIN 
(SELECT code, name, grouid,id FROM RAWtable AS DUPT GROUP BY code, name, groupid,id HAVING COUNT(*) >= 2) DUPT
 ON  DUPT.code =MAST.code and DUPT.name =MAST.name where dupt.groupid >mast.groupid 

我该怎么做?非常感谢。

4 个答案:

答案 0 :(得分:8)

select R.id,
       R.groupid,
       R.name,
       R.code
from (select id, 
             groupid, 
             name, 
             code,
             row_number() over(partition by name, code order by groupid desc) as rn
      from RawTable       
     ) as R
where R.rn = 1     

或者如果你没有row_number()

select R1.id,
       R1.groupid,
       R1.name,
       R1.code
from RawTable as R1
  inner join (  
              select name, code, max(groupid) as groupid
              from RawTable
              group by name, code
             ) as R2
    on R1.name = R2.name and
       R1.code = R2.code and
       R1.groupid = R2.groupid

答案 1 :(得分:6)

尝试这种方式,它将为您提供最新的最大组ID:

SELECT MAX(GroupId), Name, Code 
FROM RAWtable
GROUP BY Name, Code 

答案 2 :(得分:2)

select  max(id),name, code from RaTable
group by name,code having count(*)>1 

将返回:

id  name    code
2   Name1   Code1

将为表中包含多条记录的所有记录返回max gorupid

答案 3 :(得分:0)

试试这个: select max(t.groupid), t.name, t.code from RAWtable t group by t.name, t.code

这基本上会为每个名称和代码组合选择groupid的最大值。