SQL实现分组排序和组内排序

时间:2023-01-31 09:51:02

在对表做排序时,经常会遇到需要先按某一个列排序,再按这个列分组的统计值来对子组或者说其它列排序的需求,下面是一个典型案例实现的技术路径:

利用Mysql find_in_set group_concat

select * from user order by find_in_set(name,
(select group_concat(name order by time desc) from
(select name,max(time) as time from user group by name) as tt),time desc;

利用相关子查询

SELECT * ,(SELECT MAX(time) FROM user a WHERE a.name=t.NAME) AS mm
FROM user t
ORDER BY mm desc,t.time DESC