数据表ProductSales如下:

SQL动态生成列

现要实现如下效果:

SQL动态生成列

 

思路如下(主要是拼接查询字符串):

创建存储过程: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
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-01
  • 2021-09-05
  • 2021-08-30
  • 2021-07-27
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-20
  • 2021-11-09
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案