#将字段按照COLUMN1分组COLUMN2排序后分配一个从1开始升序的编号
SELECT *, ROW_NUMBER() OVER(PARTITION BY COLUMN1 ORDER BY COLUMN2 ) AS NUM FROM TABLE;
1.将商品表中的价格按升序排序并编号
SELECT goods_price,goods_user_id,ROW_NUMBER() over(ORDER BY goods_price) as num FROM goods
运行结果:
结果新增了一列来标记行号
2.将商品按用户分组后价格降序并编号
SELECT goods_price,goods_user_id,ROW_NUMBER() over(PARTITION BY goods_user_id ORDER BY goods_price desc) as num FROM goods
运行结果:
结果会按每一个用户进行分区,按价格降序排序后,按顺序编号。
3.将商品按用户分组后价格降序并编号且只查询编号为1的记录
SELECT * FROM (SELECT goods_price,goods_user_id,ROW_NUMBER() over(PARTITION By goods_user_id ORDER BY goods_price desc) as num FROM goods) as a WHERE a.num=1
运行结果:
可以看到在上述基础上过滤出了编号为1的记录。