SQL使用Apply實現row number效果

2021-10-07 13:49:23 字數 2191 閱讀 1817

sql server 2005 新增cross可以參見文章:

需求:不同班級的同學,成績對應不同等級,且不同等級的數量還不同。如1班分 90分優秀,80分良好,70中等,60分及格四擋,2班分,85分良好,60及格兩檔。

有表如下,簡易的表,如果需要輔助列可以隨便加的。

人員表eid         score          did

人員的id    獲得的分數     對應的班級id

1           90             1

2           80             1

3           72             1

4           90             2

5           80             2

6           72             2

等級表id         score          title

班級id     分數           等級名稱

1          90             優秀

1          80             良好

1          70             中等

1          60             及格

2          85             良好

2          60             及格

建立表語句:

create table students(sid int ,score int,did int )

insert into students

select 1,90,1

union

select 2,80,1

union

select 3,72,1

union

select 4,90,2

union

select 5,80,2

union

select 6,72,2

create table degres(id int ,score int,title varchar(20))

insert into degres

select 1,90,'優秀'

union

select 1,80,'良好'

union

select 1,70,'中等'

union

select 1,60,'及格'

union

select 2,85,'良好'

union

select 2,60,'及格'

實現方法一:使用row_number函式和join方法:

聯合查詢,取大於等級分數中最大的那個等級就可以了(按人分組,order by 等級分數降序,取第乙個)

實現**:

select a.sid,a.score,a.did,a.title from (

select s.*,d.title ,

row_number() over(partition by s.sid order by d.score desc) as n

from students as s

left join degres as d on s.did=d.id

where s.score>=d.score

)as a where n=1

select students.*,f.title

select top 1 deg.title from dbo.degres as deg where deg.id=students.did and students.score>=deg.score order by deg.score desc

) as f

/*eid score did title

1 90 1 優秀

2 80 1 良好

3 72 1 中等

4 90 2 良好

5 80 2 及格

6 72 2 及格

*/

答案來自csdn使用者分享:吉普賽的歌

分享論壇問題:求乙個不同班級人對應不同成績等級的查詢!

apply實現繼承

學生類本來不具備任何方法,他就具備了 person類的sayhello方法和 所有屬性。人物件 function person name,age person.prototype 輸出列印物件 function print 學生物件 function student name,age,grade,s...

apply 使用技巧

主要是傳參的不同 function thisobj argarray call 方法 function call thisobj arg1 arg2 argn var max math.max.null array var min math.min.null array 因為我們只需要用這個方法幫我...

apply的使用技巧

obj 這個物件將代替function類裡this物件 args 這是乙個陣列或者類陣列物件,它將作為引數傳給function function.call obj,param1 param2 paramn obj 這個物件將代替function類裡this物件 params 這個是乙個引數列表 a ...