Implementing grouping rankings in SQL Server

Source: Internet
Author: User

For example, we have such a table, the table name is table1, the table is stored in a class of students all the subjects of the test results, assuming the following:

Name Subjects Scores
John doe Mathematical 100
John doe Chinese 85
Tom Mathematical 95
Tom Chinese 90


At this time, the teacher asked to find out the scores of students in each subject, ranking function before we used the most is row_number () over (). However, by default, this ranking function is not a branch of the purpose, that is, not grouped, it will be all the results according to high or low ranking

SELECT *, Row_number () over (ORDER by [score] desc) as ID
From [table1] ORDER by [course]


The resulting query results are as follows:

Name Subjects Scores Ranking
John doe Mathematical 100 1
Tom Mathematical 95 2
Tom Chinese 90 3
John doe Chinese 85 4


This is not the result we want, because math and language in the ranking is meaningless. To achieve the ranking within each account, Shenyang 463 plastic Surgery Hospital Program to our proposal is row_number () over () in the use of the PARTITION by keyword, PARTITION by is the role of a specified column to group the result set first, and then rank, For example, we need to group courses in this example, so that is partition by [course], all SQL is as follows:

SELECT *, Row_number () over (PARTITION by [course] ORDER by [score] desc) as ID
From [table1] ORDER by [course]


The resulting query results are as follows:

Name Subjects Scores Ranking
John doe Mathematical 100 1
Tom Mathematical 95 2
Tom Chinese 90 1
John doe Chinese 85 2


This is the result we want.

Implementing grouping ranking in SQL Server

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.