一条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分组查询的问题分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 50新车被追尾?
- 下一篇: 潍柴3.0柴油机从增压机冒防冻液什么毛病