How to obtain the first data record by grouping SQL statements

Source: Internet
Author: User

Use the Northwind database

First, query the Employees table.

Query results:

There are only five cities in the city Column

Use ROW_NUMBER () OVER (partition by COL1 order by COL2) to group data first. Note:Group by COL1, sort by COL2 within the group, and the value calculated by this function indicates the sequential number after sorting within each group (continuous and unique in the group ).

The SQL statement is:

Select EmployeeID, LastName, FirstName, Title, TitleOfCourtesy, City, ROW_NUMBER () over (partition by City order by EmployeeID) as new_index
From Employees

Execution result diagram:

It can be seen that the group is City, and the order of the employee ID is.

Select the first record in the output Group

Execute the statement:

Select * from
(Select EmployeeID, LastName, FirstName, Title, TitleOfCourtesy, City, ROW_NUMBER () over (partition by City order by EmployeeID) as new_index
From Employees) a where a. new_index = 1

Execution result diagram:

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.