- 相关推荐
SQL面试题
1:找出公司里收入最高的前三名员工:
SQL> select rownum, last_name, salary
2 from (select last_name, salary
3 from s_emp
4 order by salary desc)
5 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
1 select last_name, salary
2 from (select rownum a, b.*
3 from s_emp b)
4* where a=3
SQL> /
LAST_NAME SALARY
------------------------- ----------
Nagayama 2660
(2):找出第三行到第五行之间的数据:
SQL> l
1 select last_name, salary
2 from (select rownum a, b.*
3 from s_emp b)
4* 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
2 from s_emp a
3 where salary>(select avg(salary)
4 from s_emp
5 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
1 select a.last_name, a.salary, a.dept_id, b.avgsal
2 from s_emp a, (select dept_id, avg(salary) avgsal
3 from s_emp
4 group by dept_id) b
5 where a.dept_id=b.dept_id
6* 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
1 select id, last_name, salary, manager_id
2 from s_emp a
3 where salary>(select salary
4 from s_emp
5* 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.