一条mysql分组查询的问题分析
Posted ShenLiang2025
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一条mysql分组查询的问题分析相关的知识,希望对你有一定的参考价值。
问题描述
请教为什么第一个query返回的数据不正确?
-- 求Department Highest Salary:
-- 第一个query:
select Department.name as Department, Employee.name as Employee, MAX(Employee. Salary) as Salary
from Employee inner join Department on Employee.departmentId = Department.id
group by DepartmentId;
-- 第二个query:
select d.name as Department, e.name as Employee, e.salary as salary
from Employee as e
inner join Department as d
on e.departmentId = d.id
inner join (
select max(salary) as Salary, departmentId
from Employee
group by departmentId
) as mx
on e.salary = mx.Salary AND e.departmentId = mx.departmentId;
问题分析
--#1 问题分析
-- Ques1:如果我们通过max、min进行分组聚合时有重复的,那么只会其中取一个(如部门里两人的工资一样)。
-- Ques2:Query1不是个正常的GROUP BY语句,在mysql可以执行,但Employee name返回的是每组里主键最小的,
-- 这和实际明显不符预期。详见#3处分析。
--#2 Way3,可以通过RANK来达到同样的效果
SELECT * FROM
(
select dept.dname as Department, emp.ename as Employee, sal,
RANK()OVER(PARTITION BY dept.deptno ORDER BY Sal DESC) rn
from emp inner join dept on emp.deptno = dept.deptno
)A
WHERE A.rn=1
/* 结果
Department Employee sal rn
ACCOUNTING KING 5000.00 1
RESEARCH FORD 3000.00 1
RESEARCH SCOTT 3000.00 1
SALES BLAKE 2850.00 1
*/
--#3 通过查看query1结果不难发现和Way3相比不仅记录数不对而且出来的Employee也对不上。
select dept.dname as Department, emp.ename as Employee,
MAX(sal)
from emp inner join dept on emp.deptno = dept.deptno
GROUP BY dept.deptno
/* 结果
Department Employee MAX(sal)
ACCOUNTING CLARK 5000.00
RESEARCH SMITH 3000.00
SALES ALLEN 2850.00
*/
-- 按部门分组,最小员工号对应的员工名称。
SELECT MIN(empno),deptno,ename FROM emp
GROUP BY deptno
/* 结果
MIN(empno) deptno ename
7782 10 CLARK
7369 20 SMITH
7499 30 ALLEN
*/
数据集
以上是关于一条mysql分组查询的问题分析的主要内容,如果未能解决你的问题,请参考以下文章