ROW_NUMBER()
功能:简单的说row_number()从1开始,为每一条分组记录返回一个数字。
用法一:
ROW_NUMBER() OVER (ORDER BY col DESC)
说明:先把col列降序,再为降序后的每条col记录返回一个序号
用法二:
ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col2 DESC)
说明:先根据col1分组,在分组内部根据col2排序,而此函数计算的值就表示每组内部排序后的顺序编号。
需求实现
需求一
怎对表sa_vehicle_count_in,根据租户(tenantId)分组,分组后获取每个分组中最新(take_time_start)的两条数据,将两条数据中指定字段的数据求和。表结构如下
首先获取分组后最新的两条数据的SQL语句如下:
SELECT
*
FROM
( SELECT *, ROW_NUMBER() over ( PARTITION BY tenantId ORDER BY take_time_start DESC ) AS row_num FROM sa_vehicle_count_in ) AS a
WHERE
row_num <= 2
然后进行分组后数据求和,sql语句如下:
SELECT
(
SUM( unknown )+ SUM( truck )+ SUM( largeBus )+ SUM( vehicle )+ SUM( van )+ SUM( buggy )+ SUM( pedestrian )+ SUM( twoWheelVehicle )+ SUM( threeWheelVehicle )+ SUM( SUVMPV )+ SUM( mediumBus )+ SUM( motorVehicle )+ SUM( nonmotorVehicle )+ SUM( smallCar )+ SUM( miniCar )+ SUM( pickupTruck )) AS sum
FROM
(
SELECT
*
FROM
( SELECT *, ROW_NUMBER() over ( PARTITION BY tenantId ORDER BY take_time_start DESC ) AS row_num FROM sa_vehicle_count_in ) AS a
WHERE
row_num <= 2
) a;
需求二
用row_number()函数对一下数据表单进行课程(cno)、分数(score)高低及学号(sno)排序
sql如下
select row_number() over(partition by cno order by score desc) ID,sno,cno,score from sc
补充说明
rank()、dense_rank()函数和row_number()函数。针对上面需求二,有时候如果第一名有两条以上的数据时,row_number()函数只会显示一个,而用rank()和dense_rank()则可以全部显示出来。
而rank()与dense_rank()函数的区别又在于,rank()会跳跃排序,而dense_rank()不会