我想在Sql查询中得到结果
id1 id2 id3 Count Id
A001 A001 A001 3
A001 NULL A001 2
A001 NULL NULL 1
答案 0 :(得分:1)
在SQL Server中,我将使用VALUES
构造:
SELECT t.*,
(SELECT COUNT(tt.ids) FROM ( VALUES (t.id1), (t.id2), (t.id3) ) tt(ids)
) as Count_Id
FROM table t;
在标准SQL中,您可以使用CASE
表达式:
SELECT t.*,
( (CASE WHEN ID1 IS NOT NULL THEN 1 ELSE 0 END) +
(CASE WHEN ID2 IS NOT NULL THEN 1 ELSE 0 END) +
(CASE WHEN ID3 IS NOT NULL THEN 1 ELSE 0 END)
) AS Count_Id
FROM table t
答案 1 :(得分:0)
您是否发现以下类似内容
select id1,id2,id3,
case when id1 is not null then 1 else 0 end+
case when id2 is not null then 1 else 0 end+
case when id3 is not null then 1 else 0 end as val