select * from table1 --行转列前格式

select * from table2 --行专列后格式

drop table table2
declare @sql varchar(max)
set @sql='select stype,newcate,cate'
select @sql=@sql+',max(case month when '''+month+''' then cast(sales as numeric(20,2)) else 0 end)['+month+'_sales]' from(select distinct month from table1 )a
set @sql=@sql+' into table2 from table1 group by stype,newcate,cate order by stype,newcate,cate '
--print(@sql) --打印代码进行检查
exec(@sql)
本文详细介绍了一种使用SQL将行数据转换为列数据的方法,通过动态SQL语句实现数据结构的灵活转换,适用于报表展示和数据分析场景。文章提供了完整的代码示例,包括创建临时表、构建动态SQL和执行SQL语句的过程。
6199

被折叠的 条评论
为什么被折叠?



