有一个表 里面很多数据(上万条), 我每一周要执行一次作业,获得某人的排名并记录下来方便后面开搞
姓名 分数 名次
CrazyFor 96840 null
DBA_Huangzj 196706 null
dawugui 432604 null
fredrickhu 296832 null
Haiwer 105563 null
happyflystone 138420 null
htl258 125853 null
josy 95658 null
liangCK 115245 null
libin_ftsafe 260840 null
paoluo 106146 null
pengdali 374373 null
qianjin036a 111430 null
roy_88 140446 null
txlicenhe 102159 null
wufeng4552 121166 null
zjcxc 878276 null
然后我要按分数进行一次排序, 并且把排序后的名次插入到[名次] 字段中, 变成这样
姓名 分数 名次
CrazyFor 96840 16
DBA_Huangzj 196706 6
dawugui 432604 2
fredrickhu 296832 4
Haiwer 105563 14
happyflystone 138420 8
htl258 125853 9
josy 95658 17
liangCK 115245 11
libin_ftsafe 260840 5
paoluo 106146 13
pengdali 374373 3
qianjin036a 111430 12
roy_88 140446 7
txlicenhe 102159 15
wufeng4552 121166 10
zjcxc 878276 1
------解决方案--------------------
update tb1 set ranking=a.tempRanking from (
select *,ROW_NUMBER() over(order by score desc) as tempRanking from tb1
) a where tb1.name=a.name and tb1.score=a.score
update tb1 set ranking=a.tempRanking from (
select *,rank() over(order by score desc) as tempRanking from tb1
) a where tb1.name=a.name and tb1.score=a.score
update tb1 set ranking=a.tempRanking from (
select *,dense_rank() over(order by score desc) as tempRanking from tb1
) a where tb1.name=a.name and tb1.score=a.score
第一種 不重複排名
第二種 跳越排名
第三種 連續排名
------解决方案--------------------
update TB1 set ranking =b.rn
from
(select *,ROW_NUMBER() over ( order by score desc) as rn from TB1) b
where TB1.name=b.name and TB1.score=b.score
go
select * from TB1
-- name score ranking
--CrazyFor 96840 16
--DBA_Huangzj 196706 6
--dawugui 432604 2
--fredrickhu 296832 4
--Haiwer 105563 14
--happyflystone 138420 8
--htl258 125853 9
--josy 95658 17
--liangCK 115245 11
--libin_ftsafe 260840 5
--paoluo 106146 13
--pengdali 374373 3
--qianjin036a 111430 12
--roy_88 140446 7
--txlicenhe 102159 15
--wufeng4552 121166 10
--zjcxc 878276 1