日期:2014-05-18  浏览次数:20607 次

如何对总分进行 “排名”
增加一个“排名”列
例如:
    ID       数学       语文       总分         排名
  1             82           83         165               2
  2             80         90         170                 1
  3             70         80         150                 3
.......................
.
.
.
其中数学   语文   的成绩都在数据表中,怎么建立一个查询   (新建一个临时表?)查询出   分数   总分   和排名   ,然后再用   控件显示   。关键是   “排名”   问题   ,不是“排序”

------解决方案--------------------
create table T(ID int, 数学 int, 语文 int)
insert T select 1, 82, 83
union all select 2, 80, 90
union all select 3, 70, 80

select *, 总分=数学+语文,排名=(select count(*) from T where (数学+语文)> =(A.数学+A.语文) ) from T as A

--result
ID 数学 语文 总分 排名
----------- ----------- ----------- ----------- -----------
1 82 83 165 2
2 80 90 170 1
3 70 80 150 3

(3 row(s) affected)
------解决方案--------------------


create table score(id int identity(1,1),math int,lang int,total int)
insert into score
select 82, 83 , 165 union all
select 80 , 90 , 170 union all
select 70 , 80 , 150


select *,sort = (select count(1) + 1 from score b where a.total < b.total)
from score a

drop table score
------解决方案--------------------
declare @t table( ID int, 数学 int, 语文 int, 总分 int)
insert into @t
select 1, 82, 83, 165 union all
select 2, 80, 90, 170 union all
select 3, 70, 80, 150
select b.*,排名=(select count(总分) from @t a where a.总分> =b.总分) from @t b order by 总分
result:
ID 数学 语文 总分 排名
----------- ----------- ----------- ----------- -----------
3 70 80 150 3
1 82 83 165 2
2 80 90 170 1

(所影响的行数为 3 行)
------解决方案--------------------
create table #t (id,math,chinese,wholesum,torder identity(1,1),trank)

insert into #t (select id,math,chinese,wholesum,0 from table1 order by wholesum desc)

declare tc cursor
for
select torder,wholesum from #t for update

declare @order int
declare @sum int
declare @tsum int
set @tsum = 0
declare @rank int
declare @trank int
set @trank = 1
open tc
fetch next from tc into @order,@sum
while @@fetch_status = 0
begin
if @tsum < @sum
set @trank = @order

set @rank = @trank

update #t set trank=@rank where current of tc

fetch next from tc into @order,@sum
end
close tc
deallocate tc

select * from #t
drop table #t

测试一下呢。这台机器上没有SQL,怕语法写错了。呵呵