1:找出公司里收入最高的前三名员工:
SQL> select rownum, last_name, salary
from (select last_name, salary
from s_emp
order by salary desc)
where rownum<=3;
ROWNUM LAST_NAME SALARY ---------- ------------------------- ----------
1 Velasquez 4750 2 Ropeburn 2945 3 Nguyen 2897.5
注意:请大家分析一下一下语句为什么不对:
SQL> select rownum, last_name, salary 2 from s_emp 3 where rownum<=3 4 order by salary desc; ROWNUM LAST_NAME SALARY ---------- ------------------------- ---------- 1 Velasquez 4750 3 Nagayama 2660 2 Ngao 2000
2: 找出表中的某一行或某几行的数据: (1):找出表中第三行数据:用以下方法是不行的,因为rownum后面至可以用<或<=号,不可以用=,>号和其它的比较符号。
SQL> select * from s_emp 2 where rownum=3;
no rows selected SQL> select * from s_emp 2 where rownum between 3 and 5; no rows selected
正确的方法如下: SQL> l
select last_name, salary
from (select rownum a, b.*
from s_emp b)
where a=3
SQL> / LAST_NAME SALARY ------------------------- ---------- Nagayama 2660
(2):找出第三行到第五行之间的数据: SQL> l
select last_name, salary
from (select rownum a, b.* from s_emp b)
where a between 3 and 5
SQL> / LAST_NAME SALARY ------------------------- ---------- Nagayama 2660 Quick-To-See 2755 Ropeburn 2945 3:找出那些工资高于他们所在部门的平均工资的员工。
(1):第一种方法: SQL> select last_name, dept_id, salary
from s_emp a
where salary>(select avg(salary) from s_emp where dept_id=a.dept_id);
LAST_NAME DEPT_ID SALARY ------------------------- ---------- ---------- Velasquez 50 4750 Urguhart 41 2280 Menchu 42 2375 Biri 43 2090 Catchpole 44 2470 Havel 45 2483.3 Nguyen 34 2897.5 Maduro 41 2660 Nozaki 42 2280 Schwartz 45 2090 10 rows selected.
(2):第二种方法: SQL> l
select a.last_name, a.salary, a.dept_id, b.avgsal
from s_emp a, (select dept_id, avg(salary) avgsal from s_emp group by dept_id) b
where a.dept_id=b.dept_id
and a.salary>b.avgsal
SQL> / LAST_NAME SALARY DEPT_ID AVGSAL ------------------------- ---------- ---------- ---------- Velasquez 4750 50 3847.5 Urguhart 2280 41 2181.5 Menchu 2375 42 2055.16667 Biri 2090 43 1710 Catchpole 2470 44 1995 Havel 2483.3 45 2069.1 Nguyen 2897.5 34 2204 Maduro 2660 41 2181.5 Nozaki 2280 42 2055.16667 Schwartz 2090 45 2069.1 10 rows selected.
4:找出那些工资高于他们所在部门的manager的工资的员工。 SQL> l
select id, last_name, salary, manager_id
from s_emp a where salary>(select salary from s_emp where id=a.manager_id)
SQL> / ID LAST_NAME SALARY MANAGER_ID ---------- ------------------------- ---------- ---------- 6 Urguhart 2280 2 7 Menchu 2375 2 8 Biri 2090 2 9 Catchpole 2470 2 10 Havel 2483.3 2 12 Giljum 2831 3 13 Sedeghi 2878.5 3 14 Nguyen 2897.5 3 15 Dumas 2755 3 16 Maduro 2660 6 10 rows selected.