MySQL分组后,组内排序
【背景和表结构】见“参考文章1.”的表结构SQL
【目的】:实现“MySQL分组后,组内排序”(这里没有考虑组内salary重复问题)
# union前后的括号很重要,没有括号会导致union前后的order by使用异常。具体原因见“参考文章3.”
(
select *
from employee
order by departmentid, salary
limit 0, 2
)
union
(
select *
from employee
order by departmentid desc, salary
limit 0, 2
)
【拓展】:后续可以考虑解决salary重复问题
- 不并列排名
- 可并列排名
- 排序序号[不能]断裂(思路见参考文章5.)
select * from employee t1 where 1 > ( select -- count(*) sum(if(t1.salary < t2.salary, 1, 0)) from employee t2 where t1.departmentid = t2.departmentId -- and t1.id = t2.id -- 小于符号“<”,统计出在当前外层条件下,有多少salary是在前面,即当前salary的排名 -- and t1.salary < t2.salary ) -- 这时候order by的作用是配合上面的子查询做间接分组! order by -- 间接实现分组 departmentid -- 不能使用id,因为id是唯一的 -- , id , salary
- 排序序号[能]断裂排序
- 排序序号[不能]断裂(思路见参考文章5.)
参考文章:
- 部门工资最高的员工(中等),https://blog.csdn.net/shine_a/article/details/128567887
- https://blog.csdn.net/shine_a/article/details/127201711?spm=1001.2014.3001.5501
- MYSQL中UNION(联合查询),https://blog.csdn.net/weixin_45909221/article/details/127956377
- MySQL中union前后不能使用order by?https://cloud.tencent.com/developer/article/2042555?from=15425&areaSource=102001.1&traceId=aBzalxUjAUft5efQWCMCf
- [MySQL] 分组排序取前N条记录以及生成自动数字序列,类似group by后 limit,https://developer.aliyun.com/article/576732