SQL - oracle - 如何从连接结果中选择特定部门

时间:2014-08-05 01:55:08

标签: sql oracle

你们可以帮我解决这个问题吗?我想修改它,以便它只向我显示这个查询中至少有3名员工的部门(78%),而不是(原始的员工/部门表)。每次我尝试"有COUNT(department_ID)或@ WHERE子句它给我一个错误。我需要做第二次加入吗?谢谢

select *
from
(
 SELECT b.employee_id, b.employee_name,b.salary, a.department_id, 
 NVL(a.department_name, 'N/A') as dept_name,
 max(b.salary) over (partition by a.department_id) as max_sal
FROM        department a, employee b
WHERE       a.department_id(+) = b.department_id
) z
WHERE salary > (max_sal*.78 )

结果:

EMPLOYEE_ID EMPLOYEE_NAME SALARY DEPARTMENT_ID DEPT_NAME MAX_SAL


   7566 JONES                      3000            10 ACCOUNTING                 3000 
   7886 STEEL                      2500            10 ACCOUNTING                 3000 
   7944 LEE                        2400            20 RESEARCH                   3000 
   7999 WOLFE                      2500            20 RESEARCH                   3000 
   7610 WILSON                     3000            20 RESEARCH                   3000 
   7921 JACKSON                    2500            30 SALES                      3000 
   7900 FISHER                     3000            30 SALES                      3000 
   7788 SCOTT                      2500            40 IT                         2900 
   7910 SMITH                      2900            40 IT                         2900 
   7603 CLARK                      4000            50 EXECUTIVE                  5000 
   7596 JOST                       4500            50 EXECUTIVE                  5000 
   7839 KING                       5000            50 EXECUTIVE                  5000 
   8000 BREWSTER                   2500               N/A                        2500 

选择了13行

         This are RESULTS I need to get:

EMPLOYEE_ID EMPLOYEE_NAME SALARY DEPARTMENT_ID DEPT_NAME MAX_SAL


   7944 LEE                        2400            20 RESEARCH                   3000 
   7999 WOLFE                      2500            20 RESEARCH                   3000 
   7610 WILSON                     3000            20 RESEARCH                   3000 
   7603 CLARK                      4000            50 EXECUTIVE                  5000 
   7596 JOST                       4500            50 EXECUTIVE                  5000 
   7839 KING                       5000            50 EXECUTIVE                  5000 

选择了6行

1 个答案:

答案 0 :(得分:1)

您可以使用另一个子查询中的分析函数进行计算:

select de.*
from (select de.*, count(*) over (partition by department_id) as cnt
      from (SELECT e.employee_id, e.employee_name, d.salary, d.department_id, 
                   NVL(d.department_name, 'N/A') as dept_name,
                   max(e.salary) over (partition by d.department_id) as max_sal
            FROM department d JOIN
                 employee e
                 ON d.department_id = e.department_id
           ) de
      where salary > max_sal*.78
     ) de
where cnt >= 3;

外部联接似乎没有必要,所以我用内部联接和现代join语法替换它。我还将表别名更改为表的缩写。它使代码更容易阅读。