求 sql语句
我的表的列名 id type type1 b1 b2 c1 c2
我想是type =A tyep1=1 的时候取 b1的值
我想是type =A tyep1=2的时候取 b2的值
我想是type =B tyep1=1的时候取 c1的值
我想是type =B tyep1=2的时候取 c2的值
[解决办法]
select case when type='A' then case when type1=1 then b1 when type1=2 then b2 end when type='B' then case when type1=1 then c1 when type1=2 then c2 end endfrom tb
[解决办法]
select *, case when type ='A' and tyep1=1 then b1 when type ='A' and tyep1=2 then b2 when type ='B' and tyep1=1 then c1 when type ='B' and tyep1=2 then c2 end from [表]
[解决办法]
create table test([id] int,[type] varchar(10),[type1] varchar(10),[b1] varchar(10),[b2] varchar(10),[c1] varchar(10),[c2] varchar(10))goinsert testselect 1,'A','1','a','a','a','a' union allselect 2,'B','2','b','a','c','d' union allselect 3,'A','2','c','e','a','d' union allselect 4,'B','1','g','a','a','e'select * from testdeclare @type varchar(10),@type1 varchar(10)set @type='B'set @type1='1'declare @sql varchar(max)select @sql=isnull(@sql,'')+' (case when [type]=''A'' and [type1]=''1'' then b1 when [type]=''A'' and [type1]=''2'' then b2 when [type]=''B'' and [type1]=''1'' then c1 when [type]=''B'' and [type1]=''2'' then b2 end) as val'print @sqlexec('select id,[type],[type1],'+@sql+' from test order by [type],[type1]' )drop table test(4 row(s) affected)id type type1 b1 b2 c1 c2----------- ---------- ---------- ---------- ---------- ---------- ----------1 A 1 a a a a2 B 2 b a c d3 A 2 c e a d4 B 1 g a a e(4 row(s) affected) (case when [type]='A' and [type1]='1' then b1 when [type]='A' and [type1]='2' then b2 when [type]='B' and [type1]='1' then c1 when [type]='B' and [type1]='2' then b2 end) as valid type type1 val----------- ---------- ---------- ----------1 A 1 a3 A 2 e4 B 1 a2 B 2 a(4 row(s) affected)