--建立测试环境
set nocount on
create table test(颜色 varchar(20),尺码 varchar(20),数量 int)
insert into test select '红','小','10'
insert into test select '红','大','10'
insert into test select '黄','中','10'
insert into test select '粉','加大','25'
insert into test select '黄','大','28'
go
create table chima(尺码 varchar(20),rowindex int)
insert into chima select '小',1
insert into chima select '中',2
insert into chima select '大',3
insert into chima select '加大',4
go
--测试
declare @sql varchar(8000)
set @sql='select 颜色 '
select @sql=@sql+',sum(case when 尺码='''+尺码+''' then 数量 else 0 end)['+尺码+']'
from (select distinct a.尺码,rowindex from test a inner join chima b on a.尺码=b.尺码
)a order by rowindex
set @sql=@sql+' from test group by 颜色'
exec(@sql)
--删除测试环境
drop table test
drop table chima
set nocount off
/*--
颜色 小 中 大 加大
-------------------- ----------- ----------- ----------- -----------
粉 0 0 0 25
红 10 0 10 0
黄 0 10 28 0
--*/