sql classic 50 questions-15. Sort according to the scores of each subject, and display the ranking. If the score is repeated, the ranking will remain vacant

table

student

sc

teacher

course

  1.  Ready to work

1.1 There are multiple fields behind group by

 

 

1.2 left join sc as b

Name sc b

 

 

1.3 left join… on a.score<b.score

The output is:

It is to loop through all the rows in table a, compared with the first row of table b, showing the rows that meet the conditions, and the columns of the row include the content of the first row of b

Cycle through all rows in table a, compare with the second row in table b, and display the rows that meet the conditions, and the column of the row includes the content of the second row of b

……

Select all rows in table a and compare them with the last row in table b.

 

 

2. Analysis process

2.1 The above data is sorted , according to the student id and classid sort

select *

from sc a

left join sc b

on a.cid = b.cid

and a.score < b.score

order by a.sid,a.cid

Here is just an interception of the results of student No. 01, and compare the results of student No. 02 with other students. Obviously, student No. 01 is a high school student. No one has higher grades in 3 subjects. Student No. 02 has 3 higher grades in Subject 01 (03, 05, 01), 4 subjects of 02 are higher than him (05, 07, 03, 01), and 2 subjects of 03 are higher than him (01, 07)

2.2 Continue to sort , and then when it is displayed, repeat when it is displayed

 

 

According to this situation

 

The score of 01 student of 01 class is 80 points, because no one is higher than him, so b.score are all null.

Then, 01 01 80 is naturally ranked first. It is count(b.score) + 1.

 

02 students 01 course 70 points, the number of rows in this prefix is ​​3. It proves that in the whole sc table, there are three students of this course with higher scores, then his name is naturally 3+1 = 4. Ok, now I understand the ranking The principle of it.

2.3 We add ranking

 

 

 

It is necessary to calculate the number of rows in this group and +1. In order to know the ranking of the first three general fields of the current group.

For example, the number of rows in the current group is 3, and the rank is 3+1=4

 

Then add the code is:

select a.cid, a.sid, a.score, count(b.score)+1 as rank

from sc as a

left join sc as b

on a.score<b.score and a.cid = b.cid

group by a.cid, a.sid,a.score

order by a.cid, rank ASC;

3. The final answer

select a.cid, a.sid, a.score, count(b.score)+1 as rank

from sc as a

left join sc as b

on a.score<b.score and a.cid = b.cid

group by a.cid, a.sid,a.score

order by a.cid, rank ASC;

 

Guess you like

Origin blog.csdn.net/liyang_nash/article/details/99641571