日期:2014-05-17 浏览次数:20428 次
if object_id('T1') IS NOT NULL
DROP table T1
go
create table T1
(
分店编码 nvarchar(20),
分店名称 nvarchar(20),
品类编码 nvarchar(20),
销售收入 int
);
insert into t1
select '002','xx分店','1100',10000.00 union all
select '002','xx分店','1300',50000.00 union all
select '003','yy分店','1100',10000.00 union all
select '003','yy分店','1300',50000.00
go
select * from t1
go
--静态
select [分店编码],[分店名称],
sum((case when 品类编码 = '1100' then 销售收入 end )) [3级品类1收入],
sum((case when 品类编码 = '1300' then 销售收入 end )) [3级品类2收入]
from t1
group by [分店编码],[分店名称]
--动态
declare @sql varchar(max)
set @sql=''
select @sql=@sql+','+ '[3级品类'+convert(nvarchar(10),row_number() over(order by 品类编码)) +'收入]' + '= sum(case when [品类编码]='+[品类编码]+' then 销售收入 else null end)'
FROM t1 GROUP BY 品类编码
exec ('select [分店编码],[分店名称]'+@sql+' from t1 group by [分店编码],[分店名称]')