Mysql按表字段分组排序,取每组数据的最值

Mysql按表字段分组排序,取每组数据的最值

  • 一、需求说明
  • 二、sql文
  • 三、rank() over()函数说明

一、需求说明

例如:有一张记录用户成绩的表 t_goal,表字段以及表数据如下:

id uuid goal time
1 56a2e88e-54f4-49f6-83dd-592ce1da63bc 90 2022-05-18 09:00:00
2 56a2e88e-54f4-49f6-83dd-592ce1da63bc 92 2022-05-19 09:00:00
3 56a2e88e-54f4-49f6-83dd-592ce1da63bc 88 2022-05-20 09:00:00
4 80be960f-cb32-4cf1-81f0-fcd5a11c92ba 92 2022-05-18 09:00:00
5 80be960f-cb32-4cf1-81f0-fcd5a11c92ba 94 2022-05-19 09:00:00
6 80be960f-cb32-4cf1-81f0-fcd5a11c92ba 96 2022-05-20 09:00:00
7 e099ba5e-27c5-4419-8bd9-7dbcb1e00cad 86 2022-05-18 09:00:00
8 e099ba5e-27c5-4419-8bd9-7dbcb1e00cad 80 2022-05-19 09:00:00
9 e099ba5e-27c5-4419-8bd9-7dbcb1e00cad 97 2022-05-20 09:00:00

需要查出每个人历史最高成绩

二、sql文

SELECT * FROM (
SELECT
DISTINCT
	uuid,
	goal,
	`time`,
	rank() over( PARTITION BY uuid ORDER BY goal DESC, `time` DESC ) rownum
FROM
	t_goal)tmp
	WHERE tmp.rownum = 1

外层未指定排序,则结果集默认按uuid,goal,time进行排序

uuid goal time
56a2e88e-54f4-49f6-83dd-592ce1da63bc 92 2022-05-19 09:00:00
80be960f-cb32-4cf1-81f0-fcd5a11c92ba 96 2022-05-20 09:00:00
e099ba5e-27c5-4419-8bd9-7dbcb1e00cad 97 2022-05-20 09:00:00

三、rank() over()函数说明

rank() over( ORDER BY goal DESC, `time` DESC )
rank() over( PARTITION BY uuid ORDER BY goal DESC, `time` DESC )

PARTITION BY:用于给结果集分组,可有多个字段。可为空。
(如果没有指定字段PARTITION BY,则把整个结果集作为一个分组)

ORDER BY:用于给结果集排序,可有多个字段

你可能感兴趣的:(数据库,mysql,数据库,database)