开发者

Get Latest ID from a Duplicate Records in a table

so i have two tables, one is RAWtable and the other is MAINtable, I have to get the latest groupID if there are more than one records exist (comparing same name, code). For example, I have this on RAWtable:

id  groupid     name        code
1   G09161405   Name1       Code1
2   G09161406   开发者_运维知识库Name1       Code1

the two records should be treated as one and should return this value only:

id  groupid     name        code
2   G09161406   Name1       Code1

This row is the only row that shiuld be inserted in the main table. Provided returning the latest GroupID (the groupid is the combination of date and time)

I've tried this but its not working:

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 

how can i do this? thanks a lot.


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     

Or if you don't have 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


Try this way, it will give you max group id which will be latest :

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


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

Will return:

id  name    code
2   Name1   Code1

Will return the max gorupid for all the records that have more than one record in the table


Try this: select max(t.groupid), t.name, t.code from RAWtable t group by t.name, t.code

This will basically select the max value of groupid for each name and code combination.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜