使用CASE语句需要SQL查询帮助

时间:2015-01-28 18:46:01

标签: sql-server tsql

create table temp (Name varchar(100), ColA int, ColB int, ColC int, ColD int)
insert into temp (name, ColA,ColB, ColC, ColD)
values ('aaaaaa',1,null,null, null)
,('bbbbbb',1,1,null,null)


select name,case 
    when ColA = 1 then 'some value'
    when ColB = 1 then 'Other value'
    when Colc = 1 then 'some2 value'
    when Cold = 1 then 'some3 value'
    end CaseValues
from temp


select * from temp

/ *当你运行这个案例时,我只得到两个记录。但是我需要为每个匹配的值创建三条记录,如下所示:

    Name    CaseValues

1   Mayur   Some value
2   anubha  some vaule
3   anubha  other value

1 个答案:

答案 0 :(得分:0)

create table V (value varchar(100), ColA int, ColB int, ColC int, ColD int)
insert into V values ('some value', 1, null, null, null)
    , ('Other value', null, 1, null, null)
    , ('some2 value', null, null, 1, null)
    , ('some3 value', null, null, null, 1)

select temp.Name, V.value
from temp
inner join V on V.colA = temp.ColA 
    or V.ColB = temp.ColB
    or V.ColC = temp.ColC
    or V.ColD = temp.ColD

Name    value
aaaaaa  some value
bbbbbb  some value
bbbbbb  Other value