SQL Server Row_number () over () takes the nth row of data for each group

Source: Internet
Author: User

Let's look at an example:

document_id card_holder_id created_date document_type_id
1 1 2015-7-1 1
2 4 2015-7-2 1
3 4 2015-7-3 5

Table:document

The general scenario is

Take the latest document_type_id of each card holder for 5 data and get the value of document_type_name (you need to join another table, not listed here).

SQL implementation:

SELECTdocument_type_id from(    --GROUP BY card holder in descending order of Created_date    SELECTrow_number () Over(PARTITION bycard_holder_idORDER  byCreated_dateDESC        )  asRow, document_type_id fromDocumentWHEREdocument_type_id= 5) asTWHERET.row= 1--the first row of data is taken here.

Defined

Returns the serial number of the expert in the result set partition, with the first row of each partition starting from 1.

Grammar

Row_number () over ([ PARTITION by [COLUMN1]] ORDER by [COLUMN2])

The green font indicates an optional, that is: Row_number () over (ORDER by [COLUMN]).

Notes    

Unless the following conditions are true, it is not guaranteed that queries that use Row_number () will return rows in exactly the same order each time they are executed.

    1. The value of the partition column is unique.

    2. The value of the ORDER by column is unique.

    3. The combination of the partition column and the value of the ORDER by column is unique.

SQL Server Row_number () over () takes the nth row of data for each 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.