我有一个包含多个列的人员表,表明该人的种族(例如非裔美国人,西班牙裔,亚洲人,白人等)。允许多种选择(例如白色和亚洲)。如果选择了特定种族,则列值为1,如果未选中则为0,如果该人完全跳过种族问题则为NULL。
我希望制定一个SELECT查询,该查询将检查多个种族列并返回单个文本值,该值是基于值为1的列的字符串连接。即,如果列White为1且列为亚洲为1,其他列为0或NULL,输出为“白/亚”。
一种方法是建立一系列涵盖所有条件组合的IF语句。但是,有8种可能的种族反应,因此IF选项似乎非常笨拙。
这个问题有一个优雅的解决方案吗?
答案 0 :(得分:2)
假设SQL Server就是这样。
select case AfricanAmerican when 1 then 'African American/' else '' end
+ case White when 1 then 'White/' else '' end
+ case Hispanic when 1 then 'Hispanic/' else '' end
from PersonTable
答案 1 :(得分:0)
这是一种有效的方法:
ISNULL(
NULLIF(
STUFF(
CASE WHEN AfricanAmerican ='1' THEN 'AfricanAmerican/' ELSE '' END
+ CASE WHEN White='1' THEN 'White/' ELSE '' END
+ CASE WHEN Asian='1' THEN 'Asian' ELSE '' END
, 1, 2, '')
,'')
, '')
As Ethnicity
答案 2 :(得分:0)
-- Some sample data.
declare @Persons as Table ( PersonId Int Identity,
AfricanAmerican Bit Null, Asian Bit Null, Hispanic Bit Null, NativeAmerican Bit Null, White Bit Null );
insert into @Persons ( AfricanAmerican, Asian, Hispanic, NativeAmerican, White ) values
( NULL, NULL, NULL, NULL, NULL ),
( 0, 0, 0, 0, 0 ),
( 1, 0, 0, 0, 0 ),
( 0, 1, 0, 0, 0 ),
( 0, 0, 1, 0, 0 ),
( 0, 0, 0, 1, 0 ),
( 0, 0, 0, 0, 1 ),
( 0, 1, 1, 1, NULL );
-- Display the results.
select PersonId, AfricanAmerican, Asian, Hispanic, NativeAmerican, White,
Substring( Ethnicity, case when Len( Ethnicity ) > 3 then 3 else 1 end,
case when Len( Ethnicity ) > 3 then Len( Ethnicity ) - 2 else 1 end ) as Ethnicity
from (
select PersonId, AfricanAmerican, Asian, Hispanic, NativeAmerican, White,
case when AfricanAmerican = 1 then ' / African American' else '' end +
case when Asian = 1 then ' / Asian' else '' end +
case when Hispanic = 1 then ' / Hispanic' else '' end +
case when NativeAmerican = 1 then ' / Native American' else '' end +
case when White = 1 then ' / White' else '' end as Ethnicity
from @Persons
) as Simone;