日期:2014-05-17  浏览次数:20471 次

求一条排名的sql
想写一个sql用于排名
比如像论坛这样积分排名:

socre    rank
800       1
700       2
700       2
500       3
500       3
200       4

有并列的,请大侠们帮忙
------解决方案--------------------
with tb(socre)
as(
select 800 union all
select 200 union all
select 300 union all
select 800 union all
select 700 union all
select 300 union all
select 800 
),source as(
select socre,rowindex=row_number()over(order by socre desc)
 from (select distinct socre from tb)tb
)
select source.* from tb,source where tb.socre=source.socre order by source.socre desc
------解决方案--------------------
with tb(score)
as(
select 800 union all
select 200 union all
select 300 union all
select 800 union all
select 700 union all
select 300 union all
select 800 
)
SELECT RANK()OVER(ORDER BY score DESC )[rank],score 
FROM tb

/*
rank                 score
-------------------- -----------
1                    800
1                    800
1                    800
4                    700
5                    300
5                    300
7                    200

(7 行受影响)
*/

------解决方案--------------------
--> 测试数据:#tb
IF OBJECT_ID('TEMPDB.DBO.#tb') IS NOT NULL DROP TABLE #tb
GO 
CREATE TABLE #tb([socre] INT)
INSERT #tb
SELECT 800 UNION ALL
SELECT 700 UNION ALL
SELECT 700 UNION ALL
SELECT 500 UNION ALL
SELECT 500 UNION ALL
SELECT 200
--------------开始查询--------------------------

SELECT *,[rank]=DENSE_RANK()OVER(ORDER BY [socre] DESC ) FROM #tb
----------------结果----------------------------
/* 
socre rank
800 1
700 2
700 2
500 3
500 3
200 4
*/