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 scores,

Assume the following:

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 (ORDERby[ score ]desc  As from[table1]ORDERby [  course ]

The resulting query results are as follows:

This is not the result we want, because math and language are ranked together without any meaning. To achieve the ranking within each account, we are going to use the Partition by keyword in row_number ()  over (), the function of Partition by is to group the result set according to a specified column, then rank, For example, we need to group courses in this example, so that is the partition by [course], all of the 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:

This is what we're looking for.

Implementing grouping rankings in SQL Server

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.