表数据是这样的
create table #t (id int ,name varchar(20),qt int,amount int)
insert #t
select 1,'aa',1,123
union
select 2,'bb',1,444
union
select 3,'cc',1,555
union
select 4,'aa',2,666
union
select 5,'bb',2,777
union
select 6,'aa',3,888
union
select 7,'bb',3,333
union
select 8,'cc',3,222
union
select 9,'aa',4,888
union
select 10,'bb',4,333
union
select 11,'cc',4,222
union
select 12,'dd',4,111

要达到如下图的效果

名次是不固定的
------解决思路----------------------
declare @sql varchar(max)='select qt,';
with cte as
(select qt,name,amount,
ROW_NUMBER()over(partition by qt order by amount desc ) as n from #t)
select @sql=@sql+'min(case [n] when '''+convert(varchar(5),[n])+'''then [name] end) as '''+QUOTENAME('name'+convert(varchar(5),[n]))+''',
min(case [n] when '''+convert(varchar(5),[n])+'''then [amount] end) as '''+QUOTENAME('amount'+convert(varchar(5),[n]))+''','
from (select distinct [N] from cte) as b
set @sql=left(@sql,len(@sql)-1)+' from (select qt,name,amount,
ROW_NUMBER()over(partition by qt order by amount desc ) as n from #t)as a group by qt'
exec(@sql)
--看着都懂,自己手动写个动态SQL还是不容易。搞搞改改。搞了10分钟了。http://www.cnblogs.com/gaizai/p/3753296.html 这个链接很好的 别人写的博客。你可以看看。没事就复习下 很好的。