我只需要获得每个城市薪水最高的员工

时间:2018-12-15 06:04:55

标签: sql oracle oracle11g

我试图获得一个新的视图,在这里我可以显示每个商店中薪水最高的员工的一个记录。

输出(所需) 显示每个商店中TOP薪水最高的员工 STORE_ID-1个没有员工,因此不在报告中

ENAME   JOB         STORE_ID    MAX(SAL)    CITY
ALLEN   SALESMAN    2           1600        New York City
KING    PRESIDENT   3           5000        Chicago
SCOTT   ANALYST     4           3000        Philadelphia

实际输出

ENAME   JOB STORE_ID    MAX(SAL)    CITY
ALLEN   SALESMAN    2   1600    New York City
TURNER  SALESMAN    2   1500    New York City
WARD    SALESMAN    2   1250    New York City
MARTIN  SALESMAN    2   1250    New York City
KING    PRESIDENT   3   5000    Chicago
BLAKE   MANAGER 3   2850    Chicago
CLARK   MANAGER 3   2450    Chicago
SCOTT   ANALYST 4   3000    Philadelphia
FORD    ANALYST 4   3000    Philadelphia
JONES   MANAGER 4   2975    Philadelphia
MILLER  CLERK   4   1300    Philadelphia
ADAMS   CLERK   4   1100    Philadelphia
JAMES   CLERK   4   950 Philadelphia
SMITH   CLERK   4   800 Philadelphia

我只能使用SELECT,GROUP BY,HAVING,ORDER BY,INNER JOIN(或其他类型的JOINS)。我不能使用分区

此查询确实产生了必要的行,但它包含其他所有行(除了最高薪的行之外)

用于商店的DDL

CREATE TABLE  "STORES" 
   (    "STORE_ID" NUMBER NOT NULL ENABLE, 
    "CITY" VARCHAR2(50), 
     PRIMARY KEY ("STORE_ID")
  USING INDEX  ENABLE
   )
/

员工的DDL

CREATE TABLE  "EMPLOYEES" 
   (    "EMPNO" NUMBER(4,0), 
    "ENAME" VARCHAR2(10), 
    "JOB" VARCHAR2(9), 
    "HIREDATE" DATE, 
    "SAL" NUMBER(7,2), 
    "COMM" NUMBER(7,2), 
    "STORE_ID" NUMBER
   )
/

CREATE INDEX  "EMP_NAME_IDEX" ON  "EMPLOYEES" ("ENAME")
/

CREATE INDEX  "EMP_NAME_JOB_DATE_IDX" ON  "EMPLOYEES" ("ENAME", "JOB", "HIREDATE")
/

第一个问题是有关错误的SQL语法的。这个人正试图在每家商店中找到薪水最高的员工

4 个答案:

答案 0 :(得分:1)

您可以使用rank窗口功能按商店的员工对他们的薪水进行排名,然后只选择排名第一的员工:

SELECT t.ename, t.job, t.sal, t.city
FROM   (SELECT e.ename, e.job, e.sal, s.city,
               RANK() OVER (PARTITION BY e.store_id ORDER BY s.sal DESC) AS rk
        FROM   employees e
        JOIN   stores s on e.store_id = s.store_id) t
WHERE  rk = 1

答案 1 :(得分:1)

Oracle对group by聚合函数有很好的扩展,可以帮助:

select max(e.ename) keep (dense_rank first order by e.sal desc) as ename,
       max(e.job) keep (dense_rank first order by e.sal desc) as ejob,
       s.store_id,
       max(e.sal) as sal
       s.city
from employee e join
     stores s
     on e.store_id = s.store_id
group by s.store_id, s.city;

答案 2 :(得分:0)

尝试使用子查询,如下所示

select e.ENAME,t1.STORE_ID,t1.sal,s.CITY from (
 SELECT  MAX(e.SAL) sal,
 e.STORE_ID FROM EMPLOYEES e    
 GROUP BY e.STORE_ID
       ) t1 join EMPLOYEES e on t1.STORE_ID =e.STORE_ID  and e.sal=t1.sal
            join STORES  s on t1.STORE_ID =s.STORE_ID 

答案 3 :(得分:0)

这将工作:

select * from (select e.ename,e.job,s.store_id,s.sal,s.city,
rank() over (partition by s.store_id order by s.sal desc) rnk 
from
employee e ,stores s
where e.store_id=s.store_id)
where rnk=1;