22,209
社区成员
发帖
与我相关
我的任务
分享
Declare @sql varchar(max)
set @sql=STUFF((select ','+QUOTENAME(CONVERT(varchar(10),[尺码],120)) from
(select [数量],[尺码],[颜色] from 尺寸表 a
inner join 颜色表 b
on a.pid=b.pid) t group by [尺码] FOR XML PATH('')) ,1,1,'')
set @sql='select * from (select [数量],[尺码],[颜色] from 尺寸表 a
inner join 颜色表 b
on a.pid=b.pid) t
pivot (sum([数量])for [尺码] in ('+@sql+')) a '
exec(@sql)
create table 颜色表
(Id varchar(20),颜色 varchar(10),pid int)
insert into 颜色表
select '1288322773','蓝色',0 union all
select '1288322773','黑色',1 union all
select '1288322773','玫红',2
create table 尺寸表
(Id varchar(20),数量 int,尺码 varchar(10),pid int)
insert into 尺寸表
select '1288322773',24,'L',0 union all
select '1288322773',18,'XL',0 union all
select '1288322773',21,'XXL',0 union all
select '1288322773',15,'L',1 union all
select '1288322773',18,'XL',1 union all
select '1288322773',19,'XXL',1 union all
select '1288322773',23,'L',2 union all
select '1288322773',20,'XL',2 union all
select '1288322773',27,'XXL',2
declare @tsql varchar(6000)
select @tsql=isnull(@tsql+',','')
+'max(case when 尺码='''+尺码+''' then 数量 else 0 end) '''+尺码+''' '
from (select distinct 尺码 from 尺寸表) t
exec('select b.颜色,'+@tsql
+' from 尺寸表 a
left join 颜色表 b on a.Id=b.Id and a.pid=b.pid
group by b.颜色,b.pid
order by b.pid ')
/*
颜色 L XL XXL
---------- ----------- ----------- -----------
蓝色 24 18 21
黑色 15 18 19
玫红 23 20 27
(3 row(s) affected)
*/
select a.颜色,
MAX(case when 尺码='L' then 数量 else null end) [L],
MAX(case when 尺码='XL' then 数量 else null end) [XL],
MAX(case when 尺码='XXL' then 数量 else null end) [XXL]
from 颜色表 a
left join 尺寸表 b
on a.pid = b.pid and a.Id = b.Id
group by a.颜色,b.pid
order by b.pid
create table 颜色表(Id int,颜色 varchar(10), pid int)
insert into 颜色表
select 1288322773 ,'蓝色' ,0 union all
select 1288322773 ,'黑色' ,1 union all
select 1288322773 ,'玫红' ,2
create table 尺寸表(Id int,数量 int, 尺码 varchar(10), pid int)
insert into 尺寸表
select 1288322773 ,24 ,'L', 0 union all
select 1288322773 ,18 ,'XL', 0 union all
select 1288322773 ,21 ,'XXL', 0 union all
select 1288322773 ,15 ,'L', 1 union all
select 1288322773 ,18 ,'XL', 1 union all
select 1288322773 ,19 ,'XXL', 1 union all
select 1288322773 ,23 ,'L', 2 union all
select 1288322773 ,20 ,'XL', 2 union all
select 1288322773 ,27 ,'XXL', 2
go
declare @sql nvarchar(4000)
set @sql = ''
select @sql = @sql + ',MAX(case when 尺码='''+b.尺码+''' then 数量 else null end) ['+b.尺码+']'
from 颜色表 a
left join 尺寸表 b
on a.pid = b.pid and a.Id = b.Id
group by b.尺码
set @sql = 'select a.颜色'+ @sql +
' from 颜色表 a
left join 尺寸表 b
on a.pid = b.pid and a.Id = b.Id
group by a.颜色,b.pid
order by b.pid'
exec(@sql)
/*
颜色 L XL XXL
蓝色 24 18 21
黑色 15 18 19
玫红 23 20 27
*/