select *,(select count(1) +1 from 分数表 where 班级 = a.班级 and moneycount> a.moneycount) as 名次
from 分数表 a

解决方案 »

  1.   

    select *,(select count(1) +1 from 分数表 where 班级 = a.班级 and moneycount> a.moneycount) as 名次 
    from 分数表 a 
    group by a.班级
      

  2.   

    if object_id('tempdb.dbo.#T') is not null drop table #T
    create table #T (ID int identity, 姓名 varchar(10), 科目 varchar(20), 分数 numeric(5,2), 班级 varchar(10))
    insert into #T
    select '张三', '语文', 80, 'A班' union all
    select '张三', '数学', 90, 'A班' union all
    select '李四', '语文', 90, 'A班' union all
    select '李四', '数学', 80, 'A班' union all
    select '赵五', '语文', 65, 'A班' union all
    select '赵五', '数学', 70, 'A班' union all
    select '钱六', '语文', 81, 'B班' union all
    select '钱六', '数学', 82, 'B班' union all
    select '孙七', '语文', 83, 'B班' union all
    select '孙七', '数学', 87, 'B班' union all
    select '王八', '语文', 85, 'B班' union all
    select '王八', '数学', 86, 'B班'if object_id('tempdb.dbo.#') is not null drop table #
    select 姓名, 班级, sum(分数)总分, 总排名=identity(int,1,1), 班排名=cast(null as int) into # from #T group by 姓名, 班级 order by 总分 desc, 姓名
    update # set 班排名=(select count(1) from # where 班级=t.班级 and 总排名<=t.总排名) from # t/*
    并列排名也有两种,一种是松散的,一种是密集的。
    下面总排名和班排名分开来写,便于观察效果:
    */select
    *,
    总松散排名=(select min(总排名) from # where 总分=t.总分),
    总密集排名=(select count(distinct 总分) from # where 总分>=t.总分)
    from # t
    /*
    姓名       班级       总分        总排名      班排名      总松散排名  总密集排名
    ---------- ---------- ----------- ----------- ----------- ----------- -----------
    王八       B班        171.00      1         1         1         1
    李四       A班        170.00      2         1         2         2
    孙七       B班        170.00      3         2         2         2
    张三       A班        170.00      4         2         2         2
    钱六       B班        163.00      5         3         5         3
    赵五       A班        135.00      6         3         6         4
    */select
    *,
    班松散排名=(select min(班排名) from # where 班级=t.班级 and 总分=t.总分),
    班密集排名=(select count(distinct 总分) from # where 班级=t.班级 and 总分>=t.总分)
    from # t
    order by 2,5/*
    姓名       班级       总分        总排名      班排名      班松散排名  班密集排名
    ---------- ---------- ----------- ----------- ----------- ----------- -----------
    李四       A班        170.00      2           1           1           1
    张三       A班        170.00      4           2           1           1
    赵五       A班        135.00      6           3           3           2
    王八       B班        171.00      1           1           1           1
    孙七       B班        170.00      3           2           2           2
    钱六       B班        163.00      5           3           3           3
    */