当前位置: 代码迷 >> Sql Server >> 排名的sql语句
  详细解决方案

排名的sql语句

热度:40   发布时间:2016-04-24 09:56:15.0
求一个排名的sql语句
表数据是这样的

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





要达到如下图的效果

名次是不固定的
------解决思路----------------------
引用:
Quote: 引用:

Quote: 引用:



qt          name1                amount1     name2                amount2     name3                amount3
----------- -------------------- ----------- -------------------- ----------- -------------------- -----------
1           cc                   555         bb                   444         aa                   123
2           bb                   777         aa                   666         NULL                 NULL
3           aa                   888         bb                   333         cc                   222
4           aa                   888         bb                   333         cc                   222
警告: 聚合或其他 SET 操作消除了 Null 值。


能不能动态点?我这里的排名是不固定的.不一定是3个..


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 这个链接很好的 别人写的博客。你可以看看。没事就复习下 很好的。
  相关解决方案