先找到未行列转换的数据,分组查看数据试试:select CompanyName,PRoductName,COUNT(*)as num from dbo.Orders group by ProductName,CompanyName order by CompanyName
去看看我给你们的分页存储过程,看看拼接sql语句字符串和执行的过程,然后把思路打开一下试试
两者结合起来,答案:
1 declare @sql varchar(8000)--声明一个字符串变量2 set @sql='select CompanyName,'--开始设置语句3 --------动态生成语句begin(开始转成列)-----4 select @sql=@sql+'sum(case when ProductName='''+ProductName+''' then num else 0 end)['+ProductName+'],' 5 from (select distinct top 100 percent ProductName from Orders order by ProductName)a6 --------动态生成语句 end--------------------7 set @sql =left(@sql,len(@sql)-1)+' from (select CompanyName,ProductName,COUNT(*)as numfrom dbo.Orders group by ProductName,CompanyName)a group by CompanyName'8 print @sql --打印输出最终执行的SQL9 exec(@sql)--执行SQL字符串