我有两张桌子
CREATE TABLE DBTEST.EMP
(
EMP_ID NUMBER,
NAME VARCHAR2(20 BYTE),
SALARY NUMBER,
DEPT_ID NUMBER,
LOC_ID NUMBER
)
CREATE TABLE DBTEST.LOC
(
LOC_ID NUMBER,
CODE VARCHAR2(3 BYTE),
DESCRIPTION VARCHAR2(100 BYTE)
)
示例数据
EMP_ID NAME SALARY DEPT_ID LOC_ID
1 Timmins 180000 1 1
2 Lauchnor 180000 1 1
4 Anderson 4 1
11 Pitcher 116000 3 2
17 Hedrick 182000 3 2
25 Mandurino 182000 2 1
69 Frenzel 62000 4 3
LOC_ID CODE DESCRIPTION
1 UT Utah
2 CA California
3 EU Europe
我想列出工资低于平均水平的员工? 注意:这是一组示例。
我希望你理解它。
由于
答案 0 :(得分:2)
这样的事情怎么样?
Select emp.*
From DBTEST.EMP emp,
(Select Avg(Salary) avg_salary, loc_id From DBTEST.EMP Group By LOC_ID) averages
Where averages.loc_id = emp.loc_id
And emp.salary < averages.avg_salary;
这符合您使用Group By
的要求,但如果给予选择,我会没有这样做,如下:
Select *
From DBTEST.EMP emp
Where salary <
(Select Avg(salary) From DBTEST.EMP emp2 Where emp2.loc_id = emp.loc_id);
这已经过测试,两个查询都会返回以下内容:
"EMP_ID","NAME","SALARY","DEPT_ID","LOC_ID"
"2","Lauchnor","180000","1","1"
"1","Timmins","180000","1","1"
"11","Pitcher","116000","3","2"
答案 1 :(得分:0)
在这种情况下,使用AVG()
作为窗口函数(Oracle术语中的分析函数)可能更容易:
SELECT * FROM (
SELECT emp_id, name, salary
, dept_id, loc_id
, AVG(salary) OVER ( PARTITION BY loc_id ) AS avg_salary
FROM emp
) WHERE salary < avg_salary;