Whenever a id has duplicate code bring back max rows, then set primary flag to 1
Table
Id,code,row_id,flag
2,0,5,-1
2,0,6,null
2,18,8,1
2,18,9,1
2,7,1,1
Results should be
Select id, code,row_id,flag,case when row_num =1 then 1 else 0 end as primary
From
( select id,code,row_id,flag, row number() over (partition by Id, prefer by row_id des) as row_num
From table
)c
The result should be
Id,code,row_id,flag,primary
2,0,6,null,0
2,18,9,1,1
2,7,1,1,0