您的位置:首页 > 数据库

sql排名有名次(刘延军 )

2011-06-11 10:19 183 查看
SELECT *,(select  count(1)+1   from 表 a where a.Num>b.Num) as 排名  from 表 b   order by 要排名的字段(Num) desc

两条关于生成排名的SQL语句:
select name,score,(select count(*) from t where score>a.score)+1
from t a
order by score
上面是:1,2,3,3,3,6,7...
下面是:1,2,3,3,3,4,5
select name,score,(select count(distinct score) from t where score>a.score)+1
from t a
order by score
http : // www. cnblogs. com/jimmyhsu/archive/2005/03/03/111884.aspx

结果可以去那里看。现在改改问题,假设这张成绩表有三个字段,姓名、成绩和排名,现在只有姓名和成绩有值,怎样将他们的排名更新上去呢?
有朋友可能会提出类似解决方案:先还是用查询语句查询出来,然后通过游标更新排名。
有没有更好的解决方案呢?当然是有的,答案就是用update语句。
update 成绩表 set 排名=(select count(*)+1 from 成绩表 where a.成绩<成绩)
from 成绩表 a
可以看到,只用一个语句就实现了。同时我们也可以发现它跟我们平常写的update语句不同,多了from。其实update语句的原理和select语句很类似,完整的update语句应该是update table set column=expression from table [where search_condition] ,可见后面的一截完全就是个查询语句。当update的table和查询的table(也就是from后面的table)完全一致的时候则可以省略,写成我们最常见的update table set column=expression [where search_condition] 。
上面仅仅是举了个例子来说明update的用法,真正在开发的时候,灵活恰当地使用update可以达到事半功倍的效果哦。
在排名次时,经常遇到取前10名,但刚好第11名(12、13...)的成绩和第10名的一样,我们必须也把后面成绩相同的也提取出来,用下面的sql语句搞定:
select top 10 with ties grade,name from result order by grade
实现读出第11、12...的核心语句是with ties
---分校排名
          select 校名,姓名,总分, (select count(*)+1 from 成绩 where 成绩.总分>a.总分 and 成绩.校名=a.校名) as 名次 from 成绩 a where 校名='XXXX学校' order by 校名,名次
          ---几个学校组合排名
          select 校名,姓名,总分, (select count(*)+1 from 成绩 where 成绩.总分>a.总分) as 名次 from 成绩 a where 校名 in ('XX1学校','XX2学校') order by 名次
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sql table search