declare @T table
(
ID int identity primary key,
FBK_ID BIGINT null,
TWT_ID BIGINT null,
LNK_ID NVARCHAR(50) null
);
每条记录只能有FBK_ID或TWT_ID或LNK_ID。没有记录在这些字段上有多个值。
因此,主要有些记录会有FacebookID值,有些记录会有TwitterID,有些记录会有LinkedInID。
问题:
什么是最快,最干净的方法呢?
选择ID,从@T
输入....其中Type是nvarchar(10)等于'Facebook'或'Twitter'或'LinkedIn',具体取决于谁有价值?
答案 0 :(得分: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>
您将获取特定社交网络的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>
答案 1 :(得分:0)
每条记录只能有FBK_ID或TWT_ID或LNK_ID。没有 记录在这些字段上有多个值。
首先修复你的桌子:
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)
)
);
最快,最干净的方法是什么?
这对我来说写得很快,使用复制+粘贴,看起来很干净:
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;