如果就是两列,上面效果是达不到的,只少还有第三列(col3),所以代码如下:
declare @str varchar(8000)
set @str=''
select @str=@str+',['+col1+']=sum(case col1 when '''+col1+
''' then col1 end)' from tb1 broup by col1
set @str='select '+stuff(@str,1,1,'')+' from tb1 group by col3'
exec(@str)
declare @s varchar(8000)
set @s = ''
select @s = @s +','+列1+'=isnull(sum(case when 列1='''+列1+''' then 列2 end),0)'
from 表 group by 列1
exec('select '+@s+' from 表)
declare @str varchar(8000)
set @str=''
select @str=@str+',['+col1+']=sum(case col1 when '''+col1+
''' then col1 end)' from tb1 broup by col1
set @str='select '+stuff(@str,1,1,'')+' from tb1 group by col1'
exec(@str)