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.
The value of the partition column is unique.
The value of the ORDER by column is unique.
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