Home > Database > Mysql Tutorial > SQL语句分组获取记录的第一条数据的方法

SQL语句分组获取记录的第一条数据的方法

WBOY
Release: 2016-06-07 18:07:56
Original
1542 people have browsed it

SQL语句分组获取记录的第一条数据的方法,使用Northwind 数据库为例子

使用Northwind 数据库

首先查询Employees表

查询结果:

city列里面只有5个城市

使用ROW_NUMBER() OVER(PARTITION BY COL1 ORDER BY COL2) 先进行分组 注:

sql语句为:

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

执行结果图:

可以看到是按照City分组,EmployeeID排序。

select出分组中的第一条记录

执行语句:

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

执行结果图:

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template