SQLTeam.com | Weblogs | Forums

How to get zplid that have two code type one code type have Null on zfeature key and another have value only without null?

I work on sql server 2012 . I face issue I can't get zplid from table #gen that have Null only zfeature key on code type and another have value only

on zfeaturekey based on zplid and codetypeid .

meaning I need to get rows that have NULL ON zfeaturekey and Values on Zfeaturekey but must be different code type but same zplid

 create table #gen
         (
         CodeTypeId int,
         Zplid  int,
         Zfeaturekey nvarchar(50)
         )
         insert into #gen values
 (854838,25820,NULL),
 (849774,25820,1502260001),
 (849774,25820,1502260016),

 (854890,28700,NULL),
 (849780,28700,1502260013),
 (849780,28700,1502260030),

 (987431,26777,1502270003),
 (987431,26777,1502280005),
 (987431,26777,1502290001),

 (987471,26720,NULL),
 (987490,26720,1502280005),
 (987490,26720,NULL)

Expcted Result :

CodeTypeId Zplid Zfeaturekey
854838 25820 NULL
849774 25820 1502260001
849774 25820 1502260016
854890 28700 NULL
849780 28700 1502260013
849780 28700 1502260030

result will be zplid 25820 and 28700 because it have more than on code type code type 854890 and have null on zfeature key

and code type 849774 and not have null only value

i will not get zplid 26777 because it Not have NULL ON zfeaturekey

i will not get zplid 26720 because it have NULL ON BOTH Code Type ON zfeaturekey

;with cte as
(select ZPLid, Sum(Case when zFeatureKey is null then 1 else 0 end) as nullzFeatureKey
from #gen
group by ZPLid
having Sum(Case when zFeatureKey is null then 1 else 0 end) > 0 ),
cteFeature as
(select ZPLid, CodeTypeID, Sum(Case when zFeatureKey is not null then 1 else 0 end) as nullzFeatureKey
from #gen
group by ZPLid, CodeTypeID
having Sum(Case when zFeatureKey is not null then 1 else 0 end) > 1)

select g.*
from #gen g
join cte c
on c.ZPLid = g.ZPLid
join cteFeature f
on c.ZPLid = f.ZPLid

thank you solved