Hi @ahmed salah ,
For different CodeTypeTo with the same PartId, you need to provide a fixed order to return the result you expect.
For different CodeTypeTo with the same PartId, you need to provide a fixed order to return the result you expect. The data you provide is actually in no order. The first row and the second row you mentioned are just data returned by sql server randomly. Therefore, currently only the following results can be achieved, that is, for PartIds with two CodeTypeTos, only one CodeTypeTo can be returned randomly:
;with except_all as
(select row_number()
over(partition by PartId
order by(select 0)) as rn, PartId
from (select PartId from #trades
where CodeTypeId in (select CodeTypeTo from #map)) t
except
select row_number()
over(partition by PartId
order by(select 0)) as rn, PartId
from (select PartId from #trades
where CodeTypeId in (select CodeTypeFrom from #map)) t)
,cte2 as
(select e.PartId,t.CodeTypeId,t.code,t.PartLevel,row_number() over(partition by t.PartId order by t.PartId) rr
from except_all e
join #trades t on e.PartId=t.PartId
where t.CodeTypeId not in (select CodeTypeFrom from #map))
select PartId,CodeTypeId,code,PartLevel from cte2
where rr<2
Output:
Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.