SQL多个案例何时和多个结果

时间:2014-10-10 12:49:00

标签: sql sql-server case-when

我有一个简化的SQL查询,如下所示:

declare @Method varchar(max);
set @Method = 'phone'

select
case 
    when @Method = 'phone' and u.PhoneNumber is not null and u.PhoneNumberConfirmed = 1 then u.PhoneNumber
    when @Method = 'email' and u.Email is not null and u.EmailConfirmed = 1 then u.Email
end,

case 
    when @Method = 'phone' and u.PhoneNumberSecondary is not null and u.PhoneNumberSecondaryConfirmed = 1 then u.PhoneNumberSecondary
    when @Method = 'email' and u.EmailSecondary is not null and u.EmailSecondaryConfirmed = 1 then u.EmailSecondary
 end

因此,它显示在2列中。我希望所有结果只有一列。我可以用这样的联盟把它分开:

...
select
case 
    when @Method = 'phone' and u.PhoneNumber is not null and u.PhoneNumberConfirmed = 1 then u.PhoneNumber
    when @Method = 'email' and u.Email is not null and u.EmailConfirmed = 1 then u.Email
end 

from
...

union

select

case 
    when @Method = 'phone' and u.PhoneNumberSecondary is not null and u.PhoneNumberSecondaryConfirmed = 1 then u.PhoneNumberSecondary
    when @Method = 'email' and u.EmailSecondary is not null and u.EmailSecondaryConfirmed = 1 then u.EmailSecondary
 end

但问题是它可能是因为它不存在任何具有PhoneNumberSecondary的行,然后我得到一个NULL行。

解决这个问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

使用UNION是正确的方法。如果您需要删除NULL,请将NULL检查添加到外部查询中:

SELECT contact_info
FROM (
select
case 
    when @Method = 'phone' and u.PhoneNumber is not null and u.PhoneNumberConfirmed = 1 then u.PhoneNumber
    when @Method = 'email' and u.Email is not null and u.EmailConfirmed = 1 then u.Email
end as contact_info
from ...
UNION
select
case 
    when @Method = 'phone' and u.PhoneNumberSecondary is not null and u.PhoneNumberSecondaryConfirmed = 1 then u.PhoneNumberSecondary
    when @Method = 'email' and u.EmailSecondary is not null and u.EmailSecondaryConfirmed = 1 then u.EmailSecondary
 end as contact_info
from ...
)
WHERE contact_info IS NOT NULL