"SQL" uses row_number () to implement group queries

Source: Internet
Author: User

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/5A/24/wKiom1T3v8zzQQ6rAACos1rMbc4635.jpg "title=" QQ picture 20150305103036.png "alt=" wkiom1t3v8zzqq6raacos1rmbc4635.jpg "/> There is a table as left, and now you need to implement the first two records that query each group (GROUPID). How is it implemented?


The first method is not explained with UNION all. However, the row_number () function can be implemented in a higher version of SQL Server with the following statement:

SELECT * FROM (select Row_number () Up (PARTITION by GroupID ORDER by id) as rowid,* from dbo.test) x WHERE ro Wid<3

Principle: The contents of the X table is based on the results of the GroupID grouping, each ROWID index is incremented in each group, such as Group 1 ROWID 1 2 3, Group 2 ROWID not 4 5 6 also starting from 1 2 3. So, the query results are as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/5A/24/wKiom1T3wMnh89cWAAC-p8RFbVY360.jpg "title=" QQ picture 20150305103445.png "alt=" Wkiom1t3wmnh89cwaac-p8rfbvy360.jpg "/>

This article is from the "PZ Technical training base" blog, please be sure to keep this source http://panzi.blog.51cto.com/4738203/1617511

"SQL" uses row_number () to implement group queries

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.