数据表ProductSales如下:
现要实现如下效果:
思路如下(主要是拼接查询字符串):
创建存储过程:SaleReport
1 Create procedure SaleReport 2 as 3 begin 4 declare @sql varchar(8000) 5 set @sql = 'select Date' 6 7 select @sql = @sql + ',isnull (sum(case Product when '''+Product+''' then SaleSum end),0) as ['+Product+']' 8 from (select distinct Product from ProductSales) as a 9 10 select @sql = @sql+' from ProductSales group by [Date]' 11 exec(@sql) 12 end
运行结果如下:
exec SaleReport
参考:https://www.cnblogs.com/ShaYeBlog/p/3594517.html