mysql語句如何寫排名 用sql語句寫排名

2021-10-17 17:13:10 字數 2471 閱讀 7931

使用sql語句求排名

表jh03有下列資料:

name score

aa  99

bb  56

cc  56

dd  77

ee  78

ff  76

gg  78

ff  50

1. 名次生成方式1 , score重複時合併名次

select * , place=(select count(distinct score) from jh03 where score >= a.score)

from jh03 a

order by place

結果name score place

aa 99.00 1

ee 78.00 2

gg 78.00 2

dd 77.00 3

ff 76.00 4

bb 56.00 5

cc 56.00 5

ff 50.00 6

2. 名次生成方式2 , score重複時保留名次空缺

select * , place=(select count(score) from jh03 where score > a.score) + 1

from jh03 a

order by place

結果name score place

aa 99.00 1

ee 78.00 2

gg 78.00 2

dd 77.00 4

ff 76.00 5

bb 56.00 6

cc 56.00 6

ff 50.00 8

--成績統計示例(交叉表)

--測試表

create table #t(xh varchar(3),xm varchar(10),km varchar(10),cj int)

insert into #t

select '001','張三','語文',80

union all select '001','張三','數學',85

union all select '002','李四','語文',90

union all select '002','李四','數學',80

union all select '003','王五','語文',70

union all select '003','王五','數學',78

--資料處理

declare @sql nvarchar(4000) , @sql1 nvarchar(4000)

select @sql = '' , @sql1 = ''

select @sql = @sql + ',[' + km + '] = sum(case km when ''' + km + ''' then cj else 0 end)'

,@sql1 = @sql1 + ',[' + km + '名次]=(select sum(1) from # where [' + km +'] >= a.[' + km + '])'

from(select distinct km from #t) a

exec('select xh 學號,xm 姓名'+@sql+',總成績=sum(cj)

,總名次=(select sum(1) from(select xh,aa=sum(cj) from #t group by xh) aa where sum(a.cj)<=aa)

into # from #t a group by xh,xm

select *'+@sql1+' from # a

drop table #t

/*--測試結果

學號 姓名 數學 語文 總成績 總名次 數學名次 語文名次

002 李四 80 90 170 1 2 1

003 王五 78 70 148 3 3 3

001 張三 85 80 165 2 1 2

其他參考寫法mysql:

selectobj_new.id,

obj_new.score,

obj_new.rownumfrom(selectobj.id,

obj.score,@rownum := @rownum + 1 asnum_tmp,@incrnum := case

when @rowtotal = obj.score then

@incrnum

when @rowtotal := obj.score then

@rownum

when @rowtotal = 0 then

@rownum :=@rownum

end asrownumfrom(selectid,

scorefromsslm_college_simulationorder byscoredesc)asobj,

(select

@rownum := 0 ,@rowtotal := null ,@incrnum := 0) r

)as obj_new

python如何寫try語句

python的try語句有兩種風格 一是處理異常 try except else 二是無論是否發生異常都將執行最後的 try finally try except else風格 try 語句 執行的 except 名字 語句 如果在try部份引發了 name 異常 except 名字 資料 語句 如...

簡單的SQL語句如何寫

use master 是首先進入系統資料庫 如果存在某個資料庫刪除這個資料庫 圖示是如果存在 digitalproductshop這個資料庫就刪除它 講位置調到當前資料庫 建立表create table 表中內容 向表中插入資料 語法insert into 表名 values 要插入的資料 查詢某個...

如何寫MySQL儲存引擎

connect to sql node link new mysqli 192.168.0.20 root world parameters for mysqli constructor are host,user,password,database if mysqli connect errno ...