//来自于别人
使用Northwind 数据库
首先查询Employees表
查询结果:
[img]http://dl2.iteye.com/upload/attachment/0101/5180/ca206dda-bae0-3cbe-85a3-9d99d2bfd2a0.jpg[/img]
city列里面只有5个城市
使用ROW_NUMBER() OVER(PARTITION BY COL1 ORDER BY COL2) 先进行分组 注:根据COL1分组,在分组内部根据 COL2排序,而此函数计算的值就表示每组内部排序后的顺序编号(组内连续的唯一的).
sql语句为:
select EmployeeID,LastName,FirstName,Title,TitleOfCourtesy,City,ROW_NUMBER() over(partition by City order by EmployeeID) as new_index
from Employees
执行结果图:
[img]http://dl2.iteye.com/upload/attachment/0101/5184/1be96a98-8f54-37b4-8a05-970b77d2cf4f.jpg[/img]
可以看到是按照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
执行结果图:
[img]http://dl2.iteye.com/upload/attachment/0101/5186/bb736312-e63b-38e5-8419-61940f50d4ab.jpg[/img]