How to get parts have duplicate on code type and different on code ?

ahmed salah 3,216 Reputation points
2021-06-03T08:07:15.543+00:00

I work on sql server 2012 I need to make select query display parts have duplicate on code type and different on code

CREATE TABLE #Trades  
(  
PartId int,  
CodeTypeId int,  
Code Int  
)  
insert into #Trades(PartId,CodeTypeId,Code)  
values  
(1215,1220,250),  
(1215,1220,110),  
(1350,1220,330),  
(1350,1220,900),  
(4521,2500,700),  
(4521,2500,800),  
(4521,2500,950),  
(3500,2900,230),  
(3500,2900,230),  
(5400,1220,230),  
(5400,1220,230)  

expected result
101999-image.png

expected result text as image above

PartId	CodeTypeId	Code  
1215	1220	250  
1215	1220	110  
1350	1220	330  
1350	1220	900  
4521	2500	700  
4521	2500	800  
4521	2500	950  
Developer technologies | Transact-SQL
SQL Server | Other
{count} votes

1 answer

Sort by: Most helpful
  1. MelissaMa-MSFT 24,221 Reputation points
    2021-06-03T08:17:58.763+00:00

    Hi @ahmed salah

    Please refer below:

    select * from  #Trades  
    where PartId in (  
    select PartId from #Trades  
    group by PartId,CodeTypeId  
    having count(distinct code) >1)  
    

    OR

    ;with cte as (  
    select PartId,CodeTypeId from #Trades  
    group by PartId,CodeTypeId  
    having count(distinct code) >1)  
    select a.*   
    from #Trades a  
    inner join cte b   
    on a.PartId=b.PartId and a.CodeTypeId=b.CodeTypeId  
    

    Output:

    PartId	CodeTypeId	Code  
    1215	1220	250  
    1215	1220	110  
    1350	1220	330  
    1350	1220	900  
    4521	2500	700  
    4521	2500	800  
    4521	2500	950  
    

    If both of above are not working, please provide more sample data and expected output.

    Best regards,
    Melissa


    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.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.