- 相關(guān)推薦
sql語句面試題
最近有許多學(xué)員問了一些面試中的問題,總結(jié)起來看,一是關(guān)于怎樣找出和去除重復(fù)數(shù)據(jù),這在另一個帖子利已有詳細(xì)介紹。二是關(guān)于找出某一列里最大或最小的前幾個,或是大于或小于某一個值(最大值或平均值)的數(shù)據(jù)。針對這種情況,再此做一個介紹。
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: 找出表中的某一行或某幾行的數(shù)據(jù):
(1):找出表中第三行數(shù)據(jù):
用以下方法是不行的,因為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):找出第三行到第五行之間的數(shù)據(jù):
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.
【sql語句面試題】相關(guān)文章:
SQL面試題07-12
數(shù)據(jù)分析人員必須掌握的一些sql語句07-10
SQL Server數(shù)據(jù)庫實訓(xùn)總結(jié)11-18
面試題與技巧07-12
華為面試題07-11
「MySQL」經(jīng)典面試題07-11
c面試題08-04
采購面試題07-11
面試題集錦07-11
Java面試題07-12