row_number() OVER (PARTITION BY COL1 ORDER BY COL2,COL3....)
一、row_number() OVER (PARTITION BY COL1 ORDER BY COL2,COL3....)
1.1、数据源显示
SELECT * FROM `partition`;
注意天明的在表中的默认顺序。
2.1、函数解释:
row_number() OVER (PARTITION BY COL1 ORDER BY COL2)
先将COL1进行分组,同名则同组,然后按照COL2排序,带出的结果就是COL2排序的顺序。第一名为1,第二名为2,以此类推。可倒序。
row_number() OVER (PARTITION BY COL1 )
先将COL1进行分组,同名则同组,然后按照COL1排序,带出的结果就是COL1排序的顺序。第一名为1,第二名为2,以此类推。可倒序。
row_number() OVER ( ORDER BY COL2)
按照COL2进行排序。
3.1、结果展示:
3.1.1 排名只有一个值,不会出现两个同名次。
注意月儿的年份排名
SELECT `name`,`year`, row_number() over (partition by `name` order by `year` desc) as '年份排名' FROM `partition`;
3.1.2 可以降序。
SELECT `name`,`year`, row_number() over (partition by `name` order by `year` ) as '年份排名' FROM `partition`;
3.1.3 不要order by
SELECT `name`,`year`, row_number() over (partition by `name` ) as '年份排名' FROM `partition`; SELECT `name`,`year`, row_number() over (partition by `name` order by `name` ) as '年份排名' FROM `partition`; --与上面结果一致
3.1.4 不要partition by
SELECT `name`,`year`, row_number() over (order by `year` ) as '年份排名' FROM `partition`;