Mssqlrow_number and partitionby grouping take the top 3 data

Source: Internet
Author: User
We often need to count the first few records with good academic performance in a table. Below we use the SQL row_number () function, row_number () the grouping and sorting function of the function makes this operation very simple. For more information, see.

We often need to count the first few records with good academic performance in a table. Below we use the SQL row_number () function, row_number () the grouping and sorting function of the function makes this operation very simple. For more information, see.

The Code is as follows:

-- 1. Create a test table
Create table # score
(
Name varchar (20 ),
Subject varchar (20 ),
Score int
)
-- 2. Insert Test Data
Insert into # score (name, subject, score) values ('zhang san', 'China', 98)
Insert into # score (name, subject, score) values ('zhang san', 'mat', 80)
Insert into # score (name, subject, score) values ('zhang san', 'English ', 90)
Insert into # score (name, subject, score) values ('Li si', 'China', 88)
Insert into # score (name, subject, score) values ('Li si', 'mat', 86)
Insert into # score (name, subject, score) values ('Li si', 'English ', 88)
Insert into # score (name, subject, score) values ('lilim', 'China', 60)
Insert into # score (name, subject, score) values ('lilim', 'mat', 86)
Insert into # score (name, subject, score) values ('Li Ming ', 'English', 88)
Insert into # score (name, subject, score) values ('lin feng', 'China', 74)
Insert into # score (name, subject, score) values ('lin feng', 'mat', 99)
Insert into # score (name, subject, score) values ('lin feng', 'English ', 59)
Insert into # score (name, subject, score) values ('yan ming', 'English ', 96)
-- 3. Retrieve the first three data entries of each subject
* From
(
Select subject, name, score, ROW_NUMBER () over (PARTITION by subject order by score desc) as num from # score
) T where T. num <= 3 order by subject
-- 4. delete a temporary table
Truncate table # score
Drop table # score

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.