1. 程式人生 > >oracle 常用sql語句

oracle 常用sql語句

onu format del 滿足 blank ica end var har

目錄

1)基本

2)數學函數

3)rownum

4)分頁

5)時間處理

6)字符函數

7)to_number

8)聚合函數

9)學生選課

10)圖書館借閱

基本

技術分享
--新建表:
create table table1( id varchar(300) primary key, name varchar(200) not null);

--插入數據   
insert into table1 (id,name) values (‘aa‘,‘bb‘);
 
--更新數據   
update table1 set id = ‘bb‘ where id=‘cc‘;
 
--刪除數據   
delete from table1 where id =‘cc‘;
 
--刪除表    
drop table table1;
 

--修改表名: 
alter table table1 rename to table2;
 
--表數據復制:
insert into table1 (select * from table2);
 
--復制表結構: 
create table table1 select * from table2 where 1>1;
 
--復制表結構和數據:
create table table1 select * from table2;
 
--復制指定字段: 
create table table1 as select id, name from table2 where 1>1;

--條件查詢: 
select id,name (case gender when 0 then ‘男‘ when 1 then ‘女’ end  ) gender from  table1 
 
技術分享

數學函數

技術分享
--絕對值:abs()
   select abs(-2) value from dual;          --(2)

--取整函數(大):ceil()
   select ceil(-2.001) value from dual;       --(-2)

--取整函數(小):floor()
   select floor(-2.001) value from dual;       --(-3)

--取整函數(截取):trunc()
   select trunc(-2.001) value from dual;       -- (-2)

--四舍五入:round()
   select round(1.234564,4) value from dual;       --(1.2346)

--取平方:Power(m,n)
   select power(4,2) value from dual;       --(16)

--取平方根:SQRT()
   select sqrt(16) value from dual;       --(4)

--取隨機數:dbms_random(minvalue,maxvalue)
   select dbms_random.value() from dual;  (默認是0到1之間)
 select dbms_random.value(2,4) value from dual;  (2-4之間隨機數)

--取符號:Sign()
  select sign(-3) value from dual; --(-1)
  select sign(3) value from dual; --(1)


--取集合的最大值:greatest(value)
   select greatest(-1,3,5,7,9) value from dual;       --(9)

--取集合的最小值:least(value)
   select least(-1,3,5,7,9) value from dual;       --(-1)

--處理Null值:nvl(空值,代替值)
   select  nvl(null,10) value from dual;       --(10)
  
   select nvl(score,10) score from student;
技術分享

rownum相關

技術分享
--rownum小於某個數時可以直接作為查詢條件(註意oracle不支持select top)
select * from student where rownum <3;

--查詢rownum大於某個數值,需要使用子查詢,並且rownum需要有別名
select * from(select rownum rn ,id,name from student) where rn>2;
select * from (select rownum rn, student.* from student) where rn >3;

--區間查詢
select * from (select rownum rn, student.* from student) where rn >3 and rn<6;

--排序+前n條
select * from (select rownum rn, t.* from ( select d.* from DJDRUVER d order  by drivernumber)t )p where p.rn<10;

--排序+區間查詢1
select * from (select rownum rn, t.* from ( select d.* from DJDRIVER d order by DJDRIVER_DRIVERTIMES)t )p where p.rn<9 and p.rn>6;

--排序+區間查詢2
select * from (select rownum rn, t.* from ( select d.* from DJDRIVER d order by DJDRIVER_DRIVERTIMES)t where rownum<9 )p where p.rn>6;--效率遠高於方式一
技術分享

分頁查詢

(假設每頁顯示10條)

不包含排序:

技術分享
--效率低

select * from (select rownum rn, d.* from DJDRIVER d  )p where p.rn<=20 and p.rn>=10;
select * from (select rownum rn, d.* from DJDRIVER d )p where p.rn between 10 and 20; --效率高 select * from (select rownum rn, d.* from DJDRIVER d where rownum<=20 )p where p.rn>=10;
技術分享

包含排序:

技術分享
--排序+區間查詢1(效率低)
select * from (select rownum rn, t.* from ( select d.* from DJDRIVER d order by DJDRIVER_DRIVERTIMES)t )p where p.rn<=20 and p.rn>=10;
select * from (select rownum rn, t.* from ( select d.* from DJDRIVER d order by DJDRIVER_DRIVERTIMES)t )p where p.rn between 10 and 20; --排序+區間查詢2(效率高)
select * from (select rownum rn, t.* from ( select d.* from DJDRIVER d order by DJDRIVER_DRIVERTIMES)t where rownum<=20 )p where p.rn>=10;
技術分享

時間處理

1. to_char和to_date基本使用

技術分享
--日期
--年 yyyy yyy yy year
--月 month mm mon month
--日+星期  dd ddd(一年中第幾天) dy day 
--小時  hh hh24 
--分 mi
--秒 ss
技術分享

eg1:

技術分享
select to_char(sysdate,‘yyyy-mm-dd hh24:mi:ss‘)currenttime, 
       to_char(sysdate,‘yyyy‘) year,
       to_char(sysdate,‘mm‘) month,
       to_char(sysdate,‘dd‘) day,
       to_char(sysdate,‘day‘) week,
       to_char(sysdate,‘hh24‘)hour,
       to_char(sysdate,‘mi‘) minute,
       to_char(sysdate,‘ss‘) second
from dual;
技術分享

技術分享

eg2:

技術分享
select to_date(‘2009-07-04 05:02:01‘,‘yyyy-mm-dd hh24:mi:ss‘)currenttime,
       to_char(to_date(‘2009-07-04 05:02:01‘,‘yyyy-mm-dd hh24:mi:ss‘),‘yyyy‘)year,
       to_char(to_date(‘2009-07-04 05:02:01‘,‘yyyy-mm-dd hh24:mi:ss‘),‘mm‘)month,
       to_char(to_date(‘2009-07-04 05:02:01‘,‘yyyy-mm-dd hh24:mi:ss‘),‘dd‘) day,
       to_char(to_date(‘2009-07-04 05:02:01‘,‘yyyy-mm-dd hh24:mi:ss‘),‘day‘) week,
       to_char(to_date(‘2009-07-04 05:02:01‘,‘yyyy-mm-dd hh24:mi:ss‘),‘day‘,‘NLS_DATE_LANGUAGE=American‘) week, --設置語言
       to_char(to_date(‘2009-07-04 05:02:01‘,‘yyyy-mm-dd hh24:mi:ss‘),‘hh24‘)hour,
       to_char(to_date(‘2009-07-04 05:02:01‘,‘yyyy-mm-dd hh24:mi:ss‘),‘mi‘) minute,
       to_char(to_date(‘2009-07-04 05:02:01‘,‘yyyy-mm-dd hh24:mi:ss‘),‘ss‘) second
from dual;
技術分享

技術分享

2)months_between

 select months_between(to_date(‘03-31-2014‘,‘MM-DD-YYYY‘),to_date(‘12-31-2013‘,‘MM-DD-YYYY‘)) "MONTHS"
 FROM DUAL;   

技術分享

3)next_day

select sysdate today, next_day(sysdate,6) nextweek from dual;

技術分享

4)時間區間

eg:

select cardid, borrowdate from borrow where to_date(borrowdate,‘yyyy-mm-dd hh24:mi:ss‘)  between 
to_date(‘2014-02-01 00:00:00‘,‘yyyy-mm-dd hh24:mi:ss‘) and 
to_date(‘2014-05-01 00:00:00‘,‘yyyy-mm-dd hh24:mi:ss‘); 

5)interval

技術分享
select to_char(sysdate,‘yyyy-mm-dd hh24:mi:ss‘) currenttime,
       to_char(sysdate - interval ‘7‘ year,‘yyyy-mm-dd hh24:mi:ss‘) intervalyear,   
       to_char(sysdate - interval ‘7‘ month,‘yyyy-mm-dd hh24:mi:ss‘) intervalMonth,   
       to_char(sysdate - interval ‘7‘ day,‘yyyy-mm-dd hh24:mi:ss‘) intervalday,   
       to_char(sysdate - interval ‘7‘ hour,‘yyyy-mm-dd hh24:mi:ss‘) intervalHour,   
       to_char(sysdate - interval ‘7‘ minute,‘yyyy-mm-dd hh24:mi:ss‘) intervalMinute,   
       to_char(sysdate - interval ‘7‘ second,‘yyyy-mm-dd hh24:mi:ss‘) intervalSecond  
  from dual; 
技術分享

技術分享

6)add_months

select add_months(sysdate,12) newtime from dual;

7)extract

 select extract(month from sysdate) "This Month",
extract(year from add_months(sysdate,36)) " Years" from dual; 

技術分享

字符函數

技術分享
--字符函數
select substr(‘abcdefg‘,1,5)substr,                     --字符串截取
       instr(‘abcdefg‘,‘bc‘) instr,                     --查找子串
       
       ‘Hello‘||‘World‘ concat,                         --連接
       
       trim(‘  wish  ‘) trim,                           --去前後空格
       rtrim(‘wish  ‘) rtrim,                           --去後面空格
       ltrim(‘  wish‘) ltrim,                           --去前面空格
       
       trim(leading ‘w‘ from ‘wish‘) deleteprefix,      --去前綴
       trim(trailing ‘h‘ from ‘wish‘) deletetrailing,   --去後綴
       trim(‘w‘ from ‘wish‘) trim1,
       
       ascii(‘A‘) A1, 
       ascii(‘a‘) A2,                                   --ascii(轉換為對應的十進制數)
       chr(65) C1, 
       chr(97) C2,                                      --chr(十進制轉對應字符)
       
       length(‘abcdefg‘) len,                           --length 
       
       lower(‘WISH‘)lower, 
       upper(‘wish‘)upper, 
       initcap(‘wish‘)initcap,                            --大小寫變換
       
       replace(‘wish1‘,‘1‘,‘youhappy‘) replace,           --替換
       
       translate(‘wish1‘,‘1‘,‘y‘)translate,               --轉換,對應一位(前面的位數大於等於後面的位數)
       translate(‘wish1‘,‘sh1‘,‘hy‘)translate1,
       
       concat(‘11‘,‘22‘) concat                     --連接

from dual;
技術分享

技術分享

to_number

技術分享
--to_number(expr)
--to_number(expr,format)
--to_number(expr,format,‘nls-param‘)

select to_number(‘0123‘)number1,            --converts a string to number
       trunc(to_number(‘0123.123‘),2) number2,
       to_number(‘120.11‘,‘999.99‘) number3,
     to_number(‘0a‘,‘xx‘) number4,        --converts a hex number to decimal
       to_number(100000,‘xxxxxx‘) number5
  
from dual;
技術分享

技術分享

聚合函數

student表如下:

技術分享

count:

--count (distinct|all)
select count(1) as count from student;--效率最高
select count(*) as count from student;    
select count(distinct score) from student;     

語句1結果:11

avg

--avg (distinct|all)
select avg(score) score from student;
select avg(distinct score) from student;
select classno,avg(score) score from student group by classno;

語句3輸出結果:

技術分享

max

--max (distinct|all)
select max(score) from student;
select classno, max(score) score from student group by classno;

min

--min (distinct|all)
select min(score) from student;
select classno, min(score) score from student group by classno;

stddev(standard deviation)標準差

--stddev
select stddev(score) from student;
select classno, stddev(score) score from student group by classno;

sum

--sum
select sum(score) from student;
select classno, sum(score) score from student group by classno;

median--中位數

--median
select median(score) from student;
select classno, median(score) score from student group by classno;

案例1--學生選課

1. 創建表 stu(學生表),course(課程表),選課表(s_c)

技術分享
--創建表

create table STU  
(  
  id   NUMBER not null,  
  name VARCHAR2(255)  
) ;
   
create table COURSE  
(  
  id  NUMBER not null,  
  coursename VARCHAR2(255)  
) ; 
   
create table S_C  
(  
  sid    NUMBER,  
  cid    NUMBER,  
  score NUMBER  
);
技術分享

2.插入數據

技術分享
--插入數據
Insert into STU (ID,NAME) values (1,‘wish‘);
Insert into STU (ID,NAME) values (2,‘rain‘);
Insert into STU (ID,NAME) values (3,‘july‘);
Insert into STU (ID,NAME) values (4,‘joey‘);

Insert into COURSE (ID,COURSENAME) values (1,‘math‘);
Insert into COURSE (ID,COURSENAME) values (2,‘english‘);
Insert into COURSE (ID,COURSENAME) values (3,‘Japanese‘);
Insert into COURSE (ID,COURSENAME) values (4,‘chinese‘);

Insert into S_C (SID,CID,SCORE) values (1,1,80);
Insert into S_C (SID,CID,SCORE) values (1,2,90);
Insert into S_C (SID,CID,SCORE) values (2,4,100);
Insert into S_C (SID,CID,SCORE) values (4,4,90);
Insert into S_C (SID,CID,SCORE) values (4,1,100);
Insert into S_C (SID,CID,SCORE) values (4,3,80);
Insert into S_C (SID,CID,SCORE) values (4,2,80);
Insert into S_C (SID,CID,SCORE) values (2,1,90);
Insert into S_C (SID,CID,SCORE) values (2,4,100);
Insert into S_C (SID,CID,SCORE) values (3,1,60);
技術分享

3.查詢學生選課情況

with vt as 
(select s.id,s.name,c.coursename,sc.score from stu s, course c, s_c sc where s.id=sc.sid and c.id=sc.cid)
select * from vt order by id;

結果:

技術分享

案例2--圖書館借閱

1.創建表: 圖書(book),讀者(reader),借閱(borrow)

技術分享
--創建表 book
create table book(
  bookId  varchar2(30),   --圖書總編號
  sortid varchar2(30),    --分類號
  bookname varchar2(100), --書名
  author varchar2(30),    --作者
  publisher varchar2(100),--出版單位
  price number(6,2)       --價格
  );
  
--創建表 reader  
create table reader (
  cardId varchar2(30),  --借書證號
  org varchar2(100),    --單位
  name varchar2(100),   --姓名
  gender varchar2(2),   --性別
  title varchar2(30),   --職稱
  address varchar2(100) --地址
);

--創建表 borrow
create table borrow(
    cardId varchar2(30),  --借書證號
  bookId  varchar2(30),   --圖書總編號
  borrowDate varchar2(30) --借閱時間
);
技術分享

2.插入數據

技術分享
--插入數據-book
insert into book (bookId,sortid,bookname,author,publisher,price) 
values (‘aaa‘,‘a1‘,‘gone with the wind‘,‘CA‘,‘renmin‘,‘103‘);

insert into book (bookId,sortid,bookname,author,publisher,price) 
values (‘bbb‘,‘a2‘,‘the little prince‘,‘CB‘,‘jixie‘,‘30‘);

insert into book (bookId,sortid,bookname,author,publisher,price) 
values (‘ccc‘,‘a3‘,‘the ordinary world‘,‘CC‘,‘renmin‘,‘130‘);

insert into book (bookId,sortid,bookname,author,publisher,price) 
values (‘ddd‘,‘a4‘,‘the little women‘,‘CA‘,‘dianzi‘,‘110‘);

--插入數據-reader
insert into reader(cardid, org, name,gender, title, address)
values (‘xxx‘,‘A‘,‘wish‘,‘1‘,‘student‘,‘bupt‘);

insert into reader(cardid, org, name,gender, title, address)
values (‘uuu‘,‘A‘,‘luna‘,‘1‘,‘student‘,‘bupt‘);

insert into reader(cardid, org, name,gender, title, address)
values (‘vvv‘,‘B‘,‘harry‘,‘1‘,‘student‘,‘bupt‘);

insert into reader(cardid, org, name,gender, title, address)
values (‘www‘,‘C‘,‘chander‘,‘2‘,‘professor‘,‘bupt‘);

insert into reader(cardid, org, name,gender, title, address)
values (‘yyy‘,‘A‘,‘joey‘,‘2‘,‘student‘,‘bupt‘);

insert into reader(cardid, org, name,gender, title, address)
values (‘zzz‘,‘B‘,‘richard‘,‘2‘,‘student‘,‘bupt‘);

insert into reader(cardid, org, name,gender, title, address)
values (‘OOO‘,‘A‘,‘micheal‘,‘2‘,‘student‘,‘bupt‘);

insert into reader(cardid, org, name,gender, title, address)
values (‘ppp‘,‘A‘,‘richal‘,‘2‘,‘student‘,‘bupt‘);

insert into reader(cardid, org, name,gender, title, address)
values (‘abp‘,‘A‘,‘michal‘,‘2‘,‘student‘,‘bupt‘);

insert into reader(cardid, org, name,gender, title, address)
values (‘ccp‘,‘A‘,‘mike‘,‘2‘,‘student‘,‘bupt‘);

--插入數據-borrow
insert into borrow(cardid,bookid,borrowdate) values(‘xxx‘,‘aaa‘,‘2014-4-29‘);
insert into borrow(cardid,bookid,borrowdate) values(‘xxx‘,‘bbb‘,‘2014-4-29‘);
insert into borrow(cardid,bookid,borrowdate) values(‘xxx‘,‘ccc‘,‘2014-4-28‘);
insert into borrow(cardid,bookid,borrowdate) values(‘yyy‘,‘ccc‘,‘2014-4-28‘);
insert into borrow(cardid,bookid,borrowdate) values(‘yyy‘,‘ddd‘,‘2014-4-27‘);
insert into borrow(cardid,bookid,borrowdate) values(‘yyy‘,‘aaa‘,‘2014-4-27‘);
insert into borrow(cardid,bookid,borrowdate) values(‘zzz‘,‘bbb‘,‘2014-4-28‘);
insert into borrow(cardid,bookid,borrowdate) values(‘zzz‘,‘ddd‘,‘2014-4-27‘);
insert into borrow(cardid,bookid,borrowdate) values(‘zzz‘,‘aaa‘,‘2014-4-27‘);
insert into borrow(cardid,bookid,borrowdate) values(‘uuu‘,‘bbb‘,‘2014-4-28‘);
insert into borrow(cardid,bookid,borrowdate) values(‘uuu‘,‘ddd‘,‘2014-4-27‘);
insert into borrow(cardid,bookid,borrowdate) values(‘uuu‘,‘aaa‘,‘2014-4-27‘);
insert into borrow(cardid,bookid,borrowdate) values(‘uuu‘,‘ccc‘,‘2014-4-26‘);
insert into borrow(cardid,bookid,borrowdate) values(‘vvv‘,‘bbb‘,‘2014-4-28‘);
insert into borrow(cardid,bookid,borrowdate) values(‘vvv‘,‘ddd‘,‘2014-4-27‘);
insert into borrow(cardid,bookid,borrowdate) values(‘www‘,‘aaa‘,‘2014-4-27‘);
insert into borrow(cardid,bookid,borrowdate) values(‘www‘,‘ccc‘,‘2014-4-26‘);
技術分享

表信息如下:

book------> reader-------> borrow

技術分享

技術分享

技術分享

3. 查詢A單位借閱圖書的讀者人數和人員詳細信息

人數:

with vt1 as 
(select cardid from reader where reader.org=‘A‘)
select count(1) from vt1 where exists (select cardid from borrow where borrow.cardid=vt1.cardid);

技術分享

詳細信息:

with vt1 as 
(select cardid,name,org from reader where reader.org=‘A‘)
select cardid,name,org from vt1 where exists (select cardid from borrow where borrow.cardid=vt1.cardid);

技術分享

4.查詢借書證號尾字符為‘p‘的讀者

select cardid, name, org from reader where cardid like ‘%p‘;

技術分享

5. 查詢名字以m開頭的女性讀者,‘1’顯示為女,‘2’顯示為男

select cardid, name, org, 
case when gender=‘1‘ then ‘女‘ when gender=‘2‘ then ‘男‘ else ‘其他‘ end gender
from reader where name like ‘m%‘;

技術分享

6. 2014年2-4月借過書的讀者

1)查詢滿足條件的讀者(僅包含cardid)--未去重

  方式一:

select cardid, borrowdate from borrow where to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘yyyy‘)=‘2014‘ 
and to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘mm‘)>=‘02‘
and to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘mm‘)<=‘04‘;

  方式二:

select cardid, borrowdate from borrow where to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘yyyy‘)=‘2014‘  --查詢
and to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘yyyy-mm‘)>=‘2014-02‘
and to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘yyyy-mm‘)<=‘2014-04‘;

  方式三:

select cardid, borrowdate from borrow where to_date(borrowdate,‘yyyy-mm-dd hh24:mi:ss‘)  between 
to_date(‘2014-02-01 00:00:00‘,‘yyyy-mm-dd hh24:mi:ss‘) and 
to_date(‘2014-05-01 00:00:00‘,‘yyyy-mm-dd hh24:mi:ss‘); 

技術分享

2) 查詢+去重

select distinct cardid from borrow where to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘yyyy‘)=‘2014‘  --查詢+去重
and to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘yyyy-mm‘)>=‘2014-02‘
and to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘yyyy-mm‘)<=‘2014-04‘;
select distinct cardid from borrow where to_date(borrowdate,‘yyyy-mm-dd hh24:mi:ss‘)  between 
to_date(‘2014-02-01 00:00:00‘,‘yyyy-mm-dd hh24:mi:ss‘) and 
to_date(‘2014-05-01 00:00:00‘,‘yyyy-mm-dd hh24:mi:ss‘); 

技術分享

3)查詢+去重+讀者姓名等信息

技術分享
with vt1 as 
(select distinct cardid from borrow where to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘yyyy‘)=‘2014‘ 
and to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘yyyy-mm‘)>=‘2014-02‘
and to_char(to_date(borrowdate,‘yyyy-mm-dd‘),‘yyyy-mm‘)<=‘2014-04‘)
select cardid, name,org from reader where exists (select cardid from vt1 where vt1.cardid=reader.cardid);
技術分享

技術分享

轉自:http://www.cnblogs.com/wishyouhappy/p/3700683.html

oracle 常用sql語句