--测试数据
create table 表(GoodsCode varchar(2),StoreCode int,GoodsSellAmount int)
insert into 表
select 'a1',1,10
union all select 'a2',1,15
union all select 'a1',2,5
union all select 'a1',3,8
go
--查询处理的存储过程
create proc p_qry
@StoreCodes varchar(1000) --要查询的StoreCode列表
as
declare @s varchar(8000),@qry nvarchar(4000)
set nocount on
select @s=''
,@qry='select @s=@s+'',[storecode''+storecode+'']=sum(case storecode when ''+storecode+'' then GoodsSellAmount else 0 end)''
from(select distinct storecode=cast(storecode as varchar) from 表 where StoreCode in('+@StoreCodes+')) a'
exec sp_executesql @qry,N'@s varchar(8000) out',@s out
exec('select GoodsCode'+@s+' from 表 where StoreCode in('
+@StoreCodes+') group by GoodsCode')
set nocount off
go
--查询处理的存储过程
create proc p_qry
@StoreCodes varchar(1000) --要查询的StoreCode列表
as
declare @s varchar(8000),@qry nvarchar(4000)
set nocount on
select @s=''
,@qry='select @s=@s+'',[storecode''+storecode+'']=sum(case storecode when ''+storecode+'' then GoodsSellAmount else 0 end)''
from(select distinct storecode=cast(storecode as varchar) from 表 where StoreCode in('+@StoreCodes+')) a'
exec sp_executesql @qry,N'@s varchar(8000) out',@s out
exec('select GoodsCode'+@s+' from 表 where StoreCode in('
+@StoreCodes+') group by GoodsCode')
set nocount off
go
是不是差不多这个意思?
if object_id('make_fun') is not null
drop procedure make_fun
go
create procedure make_fun
(@table_to_turn varchar(255), --待旋转的表
@key_col varchar(255), --保留的关键字段
@col_know_how varchar(255), --生成列名的字段
@col_to_turn varchar(255), --作为值的字段
@how_to varchar(20)='sum') --生成值的方式 sum min max avg ,etc.
/*
过程作用,根据纵向数据生成新横向结构
/
as
declare @exec varchar(8000)
create table #tmp (col varchar(255))
set @exec='select distinct '+@col_know_how+ ' from '+@table_to_turn
insert into #tmp exec (@exec)
set @exec=''
select @exec=@exec+@how_to+'(case when ['+@col_know_how+']= '''+col+''' then ['+@col_to_turn +'] else null end ) as ['+col+'],'
from #tmp
set @exec=left(@exec,len(@exec)-1)
set @exec='select ['+@key_col+'],'+@exec+' from ['+@table_to_turn+'] group by ['+@key_col+']'
--测试数据
create table 表(GoodsCode varchar(2),StoreCode int,GoodsSellAmount int)
insert into 表
select 'a1',1,10
union all select 'a2',1,15
union all select 'a1',2,5
union all select 'a1',3,8
go
--查询处理
declare @s varchar(8000)
set @s=''
select @s=@s+',[storecode'+storecode+']=sum(case storecode when '+storecode+' then GoodsSellAmount else 0 end)'
from(select distinct storecode=cast(storecode as varchar) from 表) a
exec('select GoodsCode'+@s+' from 表 group by GoodsCode')
go
declare @s varchar(8000)
set @s=''
select @s=@s+',[storecode'+storecode+']=sum(case storecode when '+storecode+' then GoodsSellAmount else 0 end)'
from(select distinct storecode=cast(storecode as varchar) from 表) a
exec('select GoodsCode'+@s+' from 表 group by GoodsCode')