《Oracle總結 06》--簡單業務操作測試
1.查詢所有員工資訊?
Select * from emp_xiangyoulu;
2.檢視所有部門資訊?
Select * from dept_xiangyoulu;
3:檢視公司工資排名的第2-5名(分頁查詢rownum )
select * from(
select rownum rn,ename,sal from emp_xiangyoulu order by sal desc)
where rn between 2 and 5;--->錯! 偽列rownum和排序order by 同時出現時,先生成偽列號,再按條件排序--->導致rn對應的序號在排序之前就定了,查出的結果和預期不符;;
SELECT ROWNUM rn,e.* FROM (
SELECT * FROM emp_xiangyoulu ORDER BY sal desc) e
WHERE rn BETWEEN 2 AND 5;--->錯! "RN": 識別符號無效,偽列號不能直接當成一般屬性直接用;
select rownum,e.* from(
select * from emp_xiangyoulu order by sal desc)e
where rownum between 2 and 5;--->錯! 不報錯,但查詢結果為0條,原因同上;
select * from(
select rownum,e.* from(
select * from emp_xiangyoulu order by sal desc)e)
where rownum between 2 and 5;--->錯! 不報錯,但查詢結果為0條,rownum沒取別名,直接用有影響;
select * from(
select rownum rn,e.* from(
select * from emp_xiangyoulu order by sal desc)e)
where rn between 2 and 5;--->結果正確!!!
3.2:檢視獎金為NULL的員工
select * from emp_xiangyoulu where comm is null;(不能用=,=只能判斷是否為" "空字串)
4.資料庫中出現兩條一樣的資料,如何只留一條?
DISTINCT關鍵字(distinct)去重;
在SELECT子句中使用,用來對指定的欄位值去除重複行。
檢視公司有哪些職位?
SELECT DISTINCT job FROM emp;
多欄位去重時,不保證單一的某個欄位的值沒有重複,而去重原則是這些欄位值的
組合沒有重複行。
SELECT DISTINCT job,deptno FROM emp
4.2 刪除除了ID之外,其他都一樣的冗餘資料(重複資料只保留一條);
delete student where (code,name) in(
select code,name from student group by code,name having count(name)>1)
and id not in(
select min(id) from student group by code,name having count(name)>1);
delete student where id not in(
select min(id) from student group by code,name);
select * from student;
5.查詢最低薪水高於30號部門最低工資的部門資訊?
SELECT deptno, MIN(sal) min_sal FROM emp
GROUP BY deptno
HAVING min_sal >(SELECT MIN(sal)
FROM emp WHERE deptno = 30);
//select deptno,MIN(sal) from emp group by deptno
hiving MIN(sal)>(select MIN(sal) from emp where deptno=30);
8.查詢部門平均薪資大於2000的所有員工資訊;
select * from emp where deptno in (
select deptno from emp group by deptno
hiving AVG(sal)>2000
);
9.查詢每個部門每種職位的員工人數;
Select count(job),deptno,job
from emp_xiangyoulu
group by rollup(deptno,job);
10:檢視從2008-08-08號到今天為止一共經歷了多少天?
SELECT SYSDATE-TO_DATE('2008-08-08','YYYY-MM-DD')
FROM DUAL;
--向上取整 ;;
--SELECT CEIL(SYSDATE-TO_DATE('2008-08-08','YYYY-MM-DD'))
FROM DUAL;
11:將每名員工入職時間以例如:(1981年12月3日的形式顯示)
select ename,to_char(hiredate, 'yyyy"年"MM"月"dd"日"')
from emp_xiangyoulu;
12:檢視SMITH的上司在哪個城市工作?(三表關聯查詢)
Select e.ename,e.mgr,m.empno,m.ename,d.loc
from emp_xiangyoulu e,emp_xiangyoulu m,dept_xiangyoulu d
Where e.mgr=m.empno and m.deptno=d.deptno and e.ename='smith';
13:檢視平均工資高於2000的那些部門名字以及所在城市?
select e.deptno,avg(e.sal),d.dname,d.loc from emp_xiangyoulu e,dept_xiangyoulu d
where e.deptno=d.deptno group by e.deptno,d.loc,d.dname having avg(e.sal)>2000;
14.在NEW YORK工作的員工有多少人?
select count(e.ename),d.loc from emp_xiangyoulu e,dept_xiangyoulu d
where e.deptno=d.deptno and d.loc='NEW YORK' group by d.loc;
15:檢視低於自己所在部門平均工資的員工?(將查詢結果作為表來關聯查詢 )
select e.ename,e.sal,d.deptno from emp_xiangyoulu e,(
select avg(sal) a_sal,deptno from emp_xiangyoulu group by deptno) d
where e.deptno=d.deptno and e.sal<d.a_sal ;