declare @sample table (list_id int, cus_id int, cus_code varchar(30), code_state varchar(30))
insert @sample
select 1,20,'x','y' union all
select 2,20,'y','y' union all
select 3,20,'e','y' union all
select 1,21,'z','y' union all
select 5,21,'A','y'
select * from @sample
insert @sample(list_id, cus_id, cus_code, code_state)
select
max(list_id),
cus_id,
'A',
'Y'
from @sample t1
where not exists(select * from @sample t2 where t2.cus_code='A' and t2.cus_id = t1.cus_id)
group by cus_id
select * from @sample
order by cus_id
Too old to Rock'n'Roll too young to die.