小编典典

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

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

该行是应插入主表中的唯一行。提供返回的最新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

我怎样才能做到这一点?多谢。


阅读 297

收藏
2021-03-10

共1个答案

小编典典

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
2021-03-10