mysql 实现先排序再分组

查询出不同性别中的年龄最大的名字
u_gender、 u_age、 u_name

GROUP_CONCAT 结合SUBSTRING_INDEX 实现

查某个字段

select SUBSTRING_INDEX(GROUP_CONCAT(u_name order by u_age desc),',',1) as username from `user` group by u_gender

查全部信息

SELECT * FROM `user`
WHERE id IN
(SELECT SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY u_age DESC),',',1) FROM user GROUP BY u_gender)

substring_index(str,delim,count)
从第一个 处开始截取之前的字符串

GROUP_CONCAT(u_name e ORDER BY u_age DESC)
合并字段到一行,且排序 用逗号分割
GROUP_CONCAT(distinct u_name separator ‘%’)
去重 用 '%'分割

先排序 在外层再分组

SELECT* from(
	SELECT powerUserId ,ifnull( u_name , 0 ) AS u_name  
	FROM user
	WHERE state = '001' AND planYM = 202405 AND compId =xxx  AND tenantId = 'xxx'
	ORDER BY u_gender,u_age  desc 
)z 
GROUP BY u_gender						

sql执行时可能会被优化导致查询结果不理想

解决方案:在里层order by 后加limit 
SELECT* from(
	SELECT powerUserId ,ifnull( u_name , 0 ) AS u_name  
	FROM user
	WHERE state = '001' AND planYM = 202405 AND compId =xxx  AND tenantId = 'xxx'
	ORDER BY u_gender,u_age  desc limit 9999
)z 
GROUP BY u_gender	

mysql版本>=8.0

select u_name,sorts from (select  u_name,dense_rank() over(partition by u_gender order by u_age desc) as sorts from `user`) as m where sorts = 1

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