MySql教程

一条mysql分组查询的问题分析

本文主要是介绍一条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
*/

数据集

SQL案例_0_员工表数据集_数据科学汇集-CSDN博客数据库数据集数据集说明这里参考Oracle的SCOTT用户下的员工信息表,该用户下有4张表。详细的员工表结构和数据见网盘链接:链接:https://pan.baidu.com/s/1CbnJSOSZPGruJBBAr3TmKQ提取码:2k0pEMP(员工的姓名、员工号、领导编号、部门编号、岗位、雇佣日期、工资、奖金等)DEPT(部门的名称、部门编号、部门所在位置)SALGRADE(工资等级、等级对应...https://shenliang.blog.csdn.net/article/details/115341944

这篇关于一条mysql分组查询的问题分析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!