简体   繁体   中英

TSQL CASE on Multiple columns

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

Each record can ONLY have either a FBK_ID or a TWT_ID or a LNK_ID. No records have multiple values on those fields.

So mainly some records will have FacebookID values, some others have TwitterID, some others have LinkedInID.

QUESTIONS :
what is the fastest and cleanest way to do this?

Select ID, Type from @T

....where Type is a nvarchar(10) equal to either 'Facebook' or 'Twitter' or 'LinkedIn' depending on who has a value?

You could do something like this:

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>

You will get back the ID and one of the link IDS for the specific social network. If you want to know, additionally, to what kind of social network does the LinkID returned belongs to, you can add an extra column as so:

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>

Each record can ONLY have either a FBK_ID or a TWT_ID or a LNK_ID. No records have multiple values on those fields.

First fix your table:

DECLARE @T TABLE
(
  ID INT IDENTITY PRIMARY KEY, 
  FBK_ID BIGINT NULL, 
  TWT_ID BIGINT NULL,
  LNK_ID NVARCHAR(50) NULL, 
  CHECK (
         (FBK_ID IS NOT NULL AND TWT_ID IS NULL AND LNK_ID IS NULL)
         OR (FBK_ID IS NULL AND TWT_ID IS NOT NULL AND LNK_ID IS NULL)
         OR (FBK_ID IS NULL AND TWT_ID IS NULL AND LNK_ID IS NOT NULL)
        )
);

what is the fastest and cleanest way to do this?

This was quite fast for me to write, employing copy+paste, and looks clean to my eye:

SELECT ID, CAST('Facebook' AS NVARCHAR(10)) AS Type
  FROM @T
 WHERE FBK_ID IS NOT NULL
UNION
SELECT ID, CAST('Twitter' AS NVARCHAR(10)) AS Type
  FROM @T
 WHERE TWT_ID IS NOT NULL
UNION
SELECT ID, CAST('LinkedIn' AS NVARCHAR(10)) AS Type
  FROM @T
 WHERE LNK_ID IS NOT NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM