我有一个表"成绩" 有如下字段 "ID"、"姓名"、"分数"、"排名"
记录情况如下:ID   姓名   分数   排名
-----------------------------
1    小李    86    1
2    小王    63    5
3    小五    75    4
4    小刘    85    2
5    小双    85    3 
6    小平    61    6   
........
....
..上面的表中ID是自动编号,姓名已输入、分数已输入,而排名字段现在是空的,上面的记录是我想得到的记录,也就是说我想通过一条SQL语句,将排名字段填写好,填写的要求是,按分数排名。请问这个按条件排名的SQL语句如何写?谢谢大家(相同分数的时候不设并列名,如上面的小刘小双同样是85分,但也不能记为并列第2名,要一个2一个3,谁2谁3都没所谓,因为我要求这个字段不能出现重名次记录,因为我在其它表要引用数据)谢谢大家

解决方案 »

  1.   

    要是我的话,我会在程序里面写……
    sql用的不是很熟~
      

  2.   


    create table t(id int,name char(20),grade int,sort int null)
    insert into t(id,name,grade)
    values(1,'小李',86)
    insert into t(id,name,grade)
    values(2,'小王',63)
    insert into t(id,name,grade)
    values(3,'小五',75)
    insert into t(id,name,grade)
    values(4,'小刘',85)
    insert into t(id,name,grade)
    values(5,'小双',85)
    insert into t(id,name,grade)
    values(6,'小平',61)select *,identity(int,1,1) as td
    into #t
    from t
    order by grade desc
    update t
    set t.sort = #t.td
    from t inner join #t
    on t.id = #t.id
    and t.grade = #t.gradedrop table #t
    select * from t
    如果是2005就不用临时表
      

  3.   

    楼上的兄弟,我的表已经存在,除"排名"这个字段以处,其它字段都已有数据,请问如何通过一句SQL语句,对"排名"字段进行更新UPDATE写入名次,谢谢
      

  4.   

    大致你可以写:declare @n int
    update [表] set @n=case when @n is null then 1 else @n+1 end,[排名]=@n order by [分数]
    以后这类问题最好在csdn 的 SQL Server 论坛上去问。
      

  5.   

    两条SQL语句写成一个查询批命令就可以了:sqlCommand.CommandText="declare @n int update [表] set @n=case when @n is null then 1 "+
      "else @n+1 end,[排名]=@n order by [分数]";
    但是如果经常变动,那么频繁更新大量数据是错误的设计。