--查詢的基本語法
select * from emp;
select *
from emp
where empno = 7369
order by sal desc
--oracle常用函數
--Oracle提供了一些可以執行特定操作的方法
--字符函數:對字符串類型的字段進行處理
select ascii('a') from dual;
--拼接字符串
select concat('hello', 'world') from dual;
select concat('h', 'w') from dual;
--獲取字符串的長度
select length(ename) from emp;
--從字符串中查找子字符串,返回位置,下標從1開始,若找不到,返回0
select instr('hello world', 'or') from dual;
--轉小寫
select ename, lower(job) from emp;
--轉大寫
select upper('hello') from dual;
--去空格
select ltrim(' hello') from dual;
--去右空格
select rtrim('hello ') from dual;
--去橫杠
select ltrim('--hello' '-') from dual;
--去掉兩邊的空格
select trim(' hello ') from dual;
--去兩邊的橫杠
select trim('-' from '--hello--') from dual;
--字符串的替換
select replace ( 'abcd', 'c', 'z' )from dual;
--截取子字符串
select substr('abcde ', 2) from dual;
--2代表起始位置,3代表截取的字符長度
select substr('ABCDE', 2, 3) from dual;
--數字函數
--求絕對值
select abs(-3) from dual;
--反余弦
select acos(1) from dual;
--余弦
select cos(1) from dual;
--大於或等於這個參數的最小值
select ceil(5.4) from dual;
--小於或者等於這個參數的最大數
select floor( - 1.2)from dual;
--求對數
select log(2, 8) from dual;
--求余數
select mod(8, 3) from dual;
--求冪數
select power(2, 3) from dual;
--四舍五入
select round(45.67) from dual;
select round(100.579, 2) from dual;
--截斷方法
select trunc(45.97) from dual;
select trunc(100.579) from dual;
--平方根
select sqrt(25) from dual;
--日期函數
--加上指定月數,返回新的日期
select hiredate, add_months(hiredate, 3) from emp;
--返回指定日期所在月的最后一天
select last_day(hiredate) from emp;
--返回兩個日期之間相隔的月數
select months_between(sysdate, hiredate) from emp;
--轉換函數*****
select to_date('1999-09-09', 'yyyy-mm-dd') from dual;
select to_char(sysdate, 'yyyy-mm-dd') from dual;
select substr(to_char(hiredate, 'yyyy-mm-dd'), 1, 4) from emp;
select to_number('123.45') from dual;
--為空值賦值
select comm + 500 from emp;
select nvl(comm, 0) from emp;
--條件判斷
select decode(job,
'CLERK','業務員' ,
'SALESMAN','銷售' ,
'MANAGER','經理')
from emp;
select case job
when 'CLERK' then
'業務員'
when 'SALESMAN' then
'銷售'
end
from emp;
--以上函數稱為單行函數
--輸入一個常量返回一個結果,或輸入一個字段名會針對每一條記錄返回一個結果
--聚合函數***************
--平均工資
select avg(sal) from emp;
--工資和
select sum(sal) from emp;
--員工數
select count(empno) from emp;
select count(*) from emp;
--最值
select max(sal) from emp;
select min(sal) from emp;
--使用了聚合函數后,不要再查詢其他字段
select ename from emp where sal = (select max(sal) from emp);
select ename from emp where sal > (select avg(sal) from emp);
--分組操作**********************
select deptno, count(empno), avg(sal), sum(sal) from emp group by deptno;
select job, avg(sal) from emp group by job;
--分組后,select只能用來查詢分組的字段和聚合函數
--平均工資大於2000的部門編號
select deptno, avg(sal) avg_sal
from emp
group by deptno
having avg(sal)
> 2000;
--各個部門下CLERK的平均工資
select deptno, avg(sal)
from emp
where job = 'CLERK'
group by deptno
having avg(sal) > 1000;
--執行順序
-->where-->group by --->having---> order by
--where 分組之前過濾,對表中全部數據進行篩選
--group by 對篩選之后的數據進行分組
--having 是篩選出符合條件的分組
--order by 是對篩選之后的分組進行排序