多列上的TSQL CASE

SF *_*per 1 sql t-sql

declare @T table
(
  ID int identity primary key, 
  FBK_ID BIGINT null, 
  TWT_ID BIGINT null,
  LNK_ID NVARCHAR(50) null
);
Run Code Online (Sandbox Code Playgroud)

每条记录只能有FBK_ID或TWT_ID或LNK_ID.没有记录在这些字段上有多个值.

所以主要有些记录会有FacebookID值,有些记录会有TwitterID,有些则有LinkedInID.

问题:
什么是最快,最干净的方法?

从@T中选择ID,类型

....其中Type是nvarchar(10)等于'Facebook'或'Twitter'或'LinkedIn',具体取决于谁有价值?

Ica*_*rus 5

你可以这样做:

select 
ID ,
case when FBK_ID is not null then FBK_ID
     when TWT_ID is not null  then  TWT_ID 
else LNK_ID end as LinkID
from @t 
where <rest of your conditions if any>
Run Code Online (Sandbox Code Playgroud)

您将获取ID和特定社交网络的链接IDS之一.此外,如果您想知道LinkID返回的社交网络属于哪种社交网络,您可以添加一个额外的列,如下所示:

select 
ID ,
case when FBK_ID is not null then FBK_ID,
     when TWT_ID is not null  then  TWT_ID 
else LNK_ID end as LinkID,
case when FBK_ID is not null then 'F'
     when TWT_ID is not null  then  'T'
else 'L' end as LinkIDFrom
from @t 
where <rest of your conditions if any>
Run Code Online (Sandbox Code Playgroud)