当其他表中的某些字段不为空时,我想从表中选择特定列。
换句话说,我有两个表,它们有共同的字段,所以当字段名为" salesordrkey"在表号1中不是null然后我需要从表号2获取公共字段,否则从表号1获取公共字段
这就是我要做的事情
Select slsordr.salesordrkey,
whissue.warehissuekey,
issuppk.issueprodpackkey,
(Case When whissue.salesordrkey Is Not Null Then
(Select slsordr.busipartnerkey,
slsordr.contractkey,
slsordr.salesmankey,
slsordr.customerkey)
Else
(Select whissue.busipartnerkey,
whissue.contractkey,
whissue.salesmankey,
slsordr.customerkey)
End)
From warehissues whissue
Inner Join issueprodpacks issuppk on whissue.warehissuekey = issuppk.warehissuekey
Left Join slssalesordrs slsordr on whissue.salesordrkey = slsordr.salesordrkey
Where
whissue.partitionkey = @prtnkey and
issuppk.prodpackkey = @prodpackkey
但是这没有用......有没有其他方法可以实现这一目标?
答案 0 :(得分:2)
我假设你的逻辑是倒退的。而不是:
case when whissue.salesordrkey is not null . . .
我想你打算:
case when slsordr.salesordrkey is not null
第一个不检查left join
是否有效。
因此,您可以使用coalesce()
:
select slsordr.salesordrkey, whissue.warehissuekey, issuppk.issueprodpackkey,
coalesce(slsordr.busipartnerkey, whissue.busipartnerkey) as busipartnerkey,
coalesce(slsordr.contractkey, whissue.contractkey) as contractkey,
coalesce(slsordr.salesmankey, whissue.salesmankey),
coalesce(slsordr.customerkey, whissue.customerkey)
from warehissues whissue inner join
issueprodpacks issuppk
on whissue.warehissuekey = issuppk.warehissuekey left join
slssalesordrs slsordr
on whissue.salesordrkey = slsordr.salesordrkey
where whissue.partitionkey = @prtnkey and
issuppk.prodpackkey = @prodpackkey
我应该注意,这不是100%完全相同的逻辑。某些匹配的记录可能在NULL
表中具有slsordr
个值。然后使用coalesce()
将引入另一个表中的值,即使存在匹配项。但是,这通常是逻辑。
否则,您需要使用多个case
语句:
(case when slsorderkey is not null then slsordr.busipartnerkey
else whissue.busipartnerkey
end) as busipartnerkey,
case
是一个表达式。它只返回一个值,而不是多个值。