SQL Server queries the first two student numbers, course Numbers, scores, and sorting of each course

Source: Internet
Author: User

Data structure introduction:

Student table (number, student ID, subject number, score)

SQL basics:

Select * from orders table

For SQL Server, the query process is one by one, that is, one record;

Then we can first think about it. When it queries the "orders table", the first query is successful before the second query;

 

Assume that the first two records of the highest score of a specific subject are queried:

Select Top 2 * from orders table where subject number = 1 order by score DESC

 

To query the first two scores of each subject, you can think like this:

When the first row is queried by the SELECT statement, the system will get the (number, student ID, subject number, and score ),

Does this record match the first two conditions for the current score being the highest score of the current subject?

The preceding method is used to obtain the first two methods, so we can proceed here:

Select student ID, subject number, score from student table as

Where student ID in

(

Select Top 2 student ID from student table as B where B. Subject no. = A. Account No.Order by score DESC

)

 

The above script can be understood:

Because the query is one by one, the (yellow area) can be understood as a condition judgment when the first data is obtained;

Whether the student ID exists in the first two of the highest scores in the current record;

The subquery part is the first two student IDs with the highest score of the current record.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.