行列转换求解释?
declare @sql as nvarchar(4000)
set @sql='select Row_number()over(order by getdate()) as id,[name]'
select @sql=@sql+',max(case rows when '+ltrim(rows)+' then items else '''' end) as row'+ltrim(rows)
from (select distinct rows from tb_VoteItem) as T
set @sql=@sql+' from tb_VoteItem group by [name]'
exec(@sql)
问题:
1、max(case rows when '+ltrim(rows)+' then items else '''' end) as row' 这句话是什么意思。
2、假如列数多了,排序就会乱,如何解决,大于10列:row0,row1,row10,row11,……
[解决办法]
group by [name] name 这里是字符串
字符串排序就是row0 row1 row10 row11 row2 这个样子的
[解决办法]
你把整个语句print @sql就知道意思了
[解决办法]
print 字符串,看结果。
[解决办法]
declare @sql as nvarchar(4000)set @sql='select Row_number()over(order by getdate()) as id,[name]'select @sql=@sql+',max(case rows when '+ltrim(rows)+' then items else '''' end) as row'+ltrim(rows) from (select distinct rows from tb_VoteItem) as Tset @sql=@sql+' from tb_VoteItem group by [name]'print @sql
[解决办法]
print出来
[解决办法]
print出来 执行下print的语句,若是有错就修改,改好你就知道动态语句错在哪了