Home > Software design >  Considering Null Values If Candidate Job Code Contains All NULLS & If Job Code is not Null consideri
Considering Null Values If Candidate Job Code Contains All NULLS & If Job Code is not Null consideri

Time:11-05

I have a table like below:

Result Set:

Candidate_Key Job_Key
913361 NULL
913361 13566
913361 13569
747197 NULL
656363 NULL
656363 12266
143143 NULL

Required Result Set

Candiate_Key Job_Key
913361 13566
913361 13569
747197 NULL
656363 12266
143143 NULL

If Candidate_Key has Job_Key value (Other than NULL) then need to retrieve Unique Job_Key's (As per the Candidate_Key [PARTITION Candidate_Key ])..........&

If Candidate_Key has only NULL values then need to retrieve First Candidate_Key and it's respective Job_Key even it's NULL

CodePudding user response:

An alternative way to accomplish this using union (although Michal's answer is probably more efficient):

declare @tbl table (
    Candidate_Key varchar(10),
    Job_Key varchar(10));

insert into @tbl
values
    (null, null),
    ('913361', null),
    ('913361', '13566'),
    ('913361', '13569'),
    ('747197', null),
    ('656363', null),
    ('656363', '12266'),
    ('143143', null);

with cte as (
    select Candidate_Key, Job_Key
    from @tbl
    where Job_Key is not null
)
--get candidates with non-null job keys
select t.*
from @tbl as t
inner join cte as c
on t.Candidate_Key = c.Candidate_Key
where t.Job_Key is not null
union
--get candidates with only null job keys
select distinct t.*
from @tbl as t
left join cte as c
on t.Candidate_Key = c.Candidate_Key
where c.Candidate_Key is null

CodePudding user response:

Here's sample query using window functions, I exapnded test data to also contain multiple NULL values for single candidate key:

declare @tbl table (Candidate_Key int, Job_Key int);
insert into @tbl values
(913361, NULL ),
(913361, 13566),
(913361, 13569),
(747197, NULL ),
(747197, NULL ),
(656363, NULL ),
(656363, 12266),
(143143, NULL );

select
    Candidate_Key,
    Job_Key
from (
    select
        Candidate_Key,
        Job_Key,
        row_number() over (partition by Candidate_Key order by Candidate_Key) rn,
        sum(case when Job_Key is null then 0 else 1 end) over (partition by Candidate_Key) notNullCnt
    from @tbl
) a 
where Job_Key is not null or (notNullCnt = 0 and rn = 1)
  • Related