SQL Server skillfully uses row_number and partition by to group top data

Source: Internet
Author: User
Tags ming

from: http://www.jb51.net/article/29162.htm
--1. Create a test tableCreate Table#score (Namevarchar( -), subjectvarchar( -), scoreint ) --2. Inserting test dataInsert  into#score (Name,subject,score)Values('Zhang San','language',98) Insert  into#score (Name,subject,score)Values('Zhang San','Mathematics', the) Insert  into#score (Name,subject,score)Values('Zhang San','English', -) Insert  into#score (Name,subject,score)Values('John Doe','language', the) Insert  into#score (Name,subject,score)Values('John Doe','Mathematics', the) Insert  into#score (Name,subject,score)Values('John Doe','English', the) Insert  into#score (Name,subject,score)Values('Li Ming','language', -) Insert  into#score (Name,subject,score)Values('Li Ming','Mathematics', the) Insert  into#score (Name,subject,score)Values('Li Ming','English', the) Insert  into#score (Name,subject,score)Values('Linfeng','language', About) Insert  into#score (Name,subject,score)Values('Linfeng','Mathematics', About) Insert  into#score (Name,subject,score)Values('Linfeng','English', -) Insert  into#score (Name,subject,score)Values('Strict','English', the) --3. Take the first 3 data from each disciplineSelect *  from ( SelectSubject,name,score,row_number () Over(PARTITION bySubjectOrder  byScoredesc) asNum from#score) TwhereT.num<= 3 Order  bysubject--4. Delete temporary tablestruncate Table#scoreDrop Table#score
Grammatical form:row_number () over (PARTITION by COL1 ORDER by COL2)
Explanation: Based on the COL1 grouping, the values in the grouping are sorted according to COL2, and the value computed by this function represents the sequential number (the only consecutive unique) result of each set within the group: --------------------------->>>
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.