填充优先于 SQL 服务器中其他列的列

Fill columns which have priority over other columns in SQL Server

我有一个 table 这样的:

id mail_1 mail_2 mail_3
1 john john_v2 john_v3
2 clarisse NULL clarisse_company
3 NULL julie NULL
4 mark markus_91 NULL
5 alfred NULL NULL

我想实现:

id mail_1 mail_2 mail_3
1 john john_v2 john_v3
2 clarisse clarisse_company NULL
3 julie NULL NULL
4 mark markus_91 NULL
5 alfred NULL NULL

如您所见,如果mail_2或mail_3不为null且mail_1为null,则mail_1应该满足。这里的问题是如果id有两封邮件,这两封邮件必须在mail_1和mail_2,而不是mail_2和mail_3,也不是mail_1和mail_3。如果一个id只有一封邮件,这封邮件必须在mail_1.

所以这里的逻辑是mail_1优先于其他两个,mail_2优先于mail_3。

如何在 SQL 服务器(版本 15)中实现这一点?

This should do. Just play by changing the values of the table variable below

declare @temp table(mail_1 varchar(20),mail_2 varchar(20),mail_3 varchar(20))

insert into @temp values(null,'middlename','lastname')

select coalesce(mail_1,mail_2,mail_3) as mail_1,
case when mail_1 
is null and mail_2 is not null then mail_3
when mail_1 
is not null and mail_2 is  null 
 then
mail_3 
else mail_2 end mail_2,
case when (mail_1 is null or mail_2 is null) then null else mail_3 end mail_3
from @temp