当前位置: 代码迷 >> Sql Server >> 行转列汇总,该怎么解决
  详细解决方案

行转列汇总,该怎么解决

热度:90   发布时间:2016-04-27 13:39:55.0
行转列汇总
产品编号 区间 销量
10001 201203 30
10001 201201 40
10001 201202 50
10002 201201 10
10002 201202 20
10002 201203 30

如何将上述数据写入到,现有如下的数据表中
如果本月是2月份
产品 M-1月 M月 M+1月  
10001 40 50 30
10002 10 20 30

------解决方案--------------------
SQL code
--> 测试数据:[tbl]if object_id('[tbl]') is not null drop table [tbl]create table [tbl]([产品编号] int,[区间] varchar(6),[销量] int)insert [tbl]select 10001,'201203',30 union allselect 10001,'201201',40 union allselect 10001,'201202',50 union allselect 10002,'201201',10 union allselect 10002,'201202',20 union allselect 10002,'201203',30declare @str varchar(max)set @str=''select @[email protected]+','+'['+RIGHT([区间],2)+'月]'+'=max(case when RIGHT([区间],2)='+QUOTENAME(RIGHT([区间],2),'''')+' then [销量] else 0 end)' from tblgroup by RIGHT([区间],2)exec('select [产品编号][email protected]+' from tbl group by [产品编号]')/*产品编号    01月    02月    03月10001    40    50    3010002    10    20    30*/
------解决方案--------------------
SQL code
--> 测试数据:[tbl]if object_id('[tbl]') is not null drop table [tbl]create table [tbl]([产品编号] int,[区间] varchar(6),[销量] int)insert [tbl]select 10001,'201203',30 union allselect 10001,'201201',40 union allselect 10001,'201202',50 union allselect 10002,'201201',10 union allselect 10002,'201202',20 union allselect 10002,'201203',30 union allselect 10002,'201204',30 union allselect 10001,'201203',30goif OBJECT_ID('pro_tracy')is not nulldrop proc pro_tracygocreate proc pro_tracyascreate table #t([产品编号] int,[区间] varchar(6),[销量] int)insert #tselect * from tbl where cast(RIGHT([区间],2) as Int) between MONTH(GETDATE())-1 and MONTH(GETDATE())+1declare @str varchar(max)set @str=''select @[email protected]+','+'['+RIGHT([区间],2)+'月]'+'=max(case when RIGHT([区间],2)='+QUOTENAME(RIGHT([区间],2),'''')+' then [销量] else 0 end)' from #tgroup by RIGHT([区间],2)exec('select [产品编号][email protected]+' from #t group by [产品编号]')--修改了你的数据exec pro_tracy/*产品编号    02月    03月    04月10001    50    30    010002    20    30    30*/
  相关解决方案