日期:2014-05-18 浏览次数:20671 次
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 end from 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)) go insert test select 1,'A','1','a','a','a','a' union all select 2,'B','2','b','a','c','d' union all select 3,'A','2','c','e','a','d' union all select 4,'B','1','g','a','a','e' select * from test declare @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 @sql exec('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 a 2 B 2 b a c d 3 A 2 c e a d 4 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 val id type type1 val ----------- ---------- ---------- ---------- 1 A 1 a 3 A 2 e 4 B 1 a 2 B 2 a (4 row(s) affected)