[英]Considering Null Values If Candidate Job Code Contains All NULLS & If Job Code is not Null considering other values
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 ])..........&如果 Candidate_Key 具有 Job_Key 值(非 NULL),则需要检索唯一的 Job_Key(根据 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如果 Candidate_Key 只有 NULL 值,则需要检索 First Candidate_Key 并且它是相应的 Job_Key,即使它是 NULL
An alternative way to accomplish this using union (although Michal's answer is probably more efficient):使用 union 完成此操作的另一种方法(尽管 Michal 的回答可能更有效):
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
Here's sample query using window functions, I exapnded test data to also contain multiple NULL
values for single candidate key:这是使用窗口函数的示例查询,我将测试数据扩展为还包含单个候选键的多个
NULL
值:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.