SQL子查询多个值

时间:2013-02-14 13:23:44

标签: sql oracle

我只需要一些关于SQL查询的帮助

这是情况

ID   FIRST_NAME LAST_NAME  START_DAT END_DATE  SALARY     CITY       DESCRIPTION
---- ---------- ---------- --------- --------- ---------- ---------- ---------------
01   Jason      Martin     25-JUL-96 25-JUL-06 1234.56    Toronto    Programmer
02   Alison     Mathews    21-MAR-76 21-FEB-86 6661.78    Vancouver  Tester
03   James      Smith      12-DEC-78 15-MAR-90 6544.78    Vancouver  Tester
04   Celia      Rice       24-OCT-82 21-APR-99 2344.78    Vancouver  Manager
05   Robert     Black      15-JAN-84 08-AUG-98 2334.78    Vancouver  Tester
06   Linda      Green      30-JUL-87 04-JAN-96 4322.78    New York   Tester
07   David      Larry      31-DEC-90 12-FEB-98 7897.78    New York   Manager
08   James      Cat        17-SEP-96 15-APR-02 1232.78    Vancouver  Tester

8 rows selected.

SQL> -- GROUP BY clause and AVG() function

SQL> SELECT city, AVG(salary)
2 FROM employee
3 GROUP BY city;


CITY AVG(SALARY)
---------- -----------
New York 6110.28

Toronto 1234.56

Vancouver 3823.78

问题是我找不到从城市每个avg(salary)中提取工资较高的名字的方法

示例:

温哥华的avg(salary)为3823.78,所以我应该得到两个人的名字:艾莉森和詹姆斯,因为他们的工资高于纽约的avg(salary)

现在我只转到这个查询但没有工作

select FIRST_NAME,SALARY,CITY 
from employee 
where SALARY > (  select avg(SALARY) 
                  from employee 
                  group by CITY
                );

它告诉我子查询返回的值超过1

希望有人可以帮助我

1 个答案:

答案 0 :(得分:2)

您的查询返回多个值。要将其限制为一个值,您需要city上的条件:

select FIRST_NAME,SALARY,CITY
from employee e
where SALARY > (select avg(SALARY) 
                from employee e2 
                where e2.city = e.city 
                group by CITY);

这称为相关子查询。您也可以将其编写为连接,这是我将使用的语法。严格来说,group by CITY是不必要的,但我认为它使子查询的意图更加清晰。

您可以通过执行以下操作将其重写为联接:

select e.FIRST_NAME, e.SALARY, e.CITY
from employee e join
     (select city, avg(salary) as avgSalary
      from employee
      group by city
     ) ec
     on e.city = ec.city
where e.salary > ec.avgSalary

或者,我最喜欢的方式是什么。 。

select e.FIRST_NAME, e.SALARY, e.CITY
from (select e.*,
             avg(salary) over (partition by city) as avgSalary
      employee e
     ) e
where e.salary > e.avgSalary