0、写在前面(把学到的PLSQL-Procedural Language/SQL记下来,陆续更新吧)
(1)用col_1代表’字段名’,tbl_1代表’表名’
(2)
表名:tbl_1
NO | ITEMCODE | NAME | MDATE | MTIME | QTY | STATUS |
---|---|---|---|---|---|---|
1 | 15001 | 初号机 | 20190815 | 164200 | 100 | OK |
2 | 15001 | 初号机 | 20190815 | 80102 | 200 | NG |
3 | 15002 | 二号机 | 20190810 | 131416 | 300 | OK |
4 | 2233 | 3322 | 20190101 | 520 | 123 |
-
Select语句
(1)、这应该是SQL里最基本的语句了。
(2)、基本写法是select * from tbl_1
,将tbl_1里全部的字段名全部展示出来。
(3)、select itemcode from tbl_1
,将tbl_1表里的itemcode字段查出来,并只显示itemcode这一列。 -
Where语句
(1)、指定一些条件从表内筛选出来一些记录。
(2)、select * from tbl_1 where itemcode = '2233'
。将表tb_1中列itemcode里数据是2233的记录展示出来。 -
Update语句
Update语句有两种写法。
(1)、第一种是在select后面加for update。
select * from tbl_1 where col_1 ='2233' for update
这条语句会将表tb_1中列col_1里数据是2233的记录展示出来,点击锁(Edit data),就可以修改展示出来的字段。
(2)、第二种就是用Update,Update tbl_1 set col_1 = '3322' where col_1 ='2233'
将表中tbl_1的列col_1的值未2233的替换为3322。 -
and和or运算符
(1)、在where语句中要并列拼接多个条件的时候需要and或者or运算符,and为并列,且的意思。or是或者。
(2)、select * from tbl_1 where (col_1 ='2233' or col_1 ='3322') and col_2 = 'OK'
将表tbl_1中列col_1是2233或者3322,且列col_2是OK的结果展示出来。 -
Order by
(1)、order by 用于对字母或者数字进行排序,desc是从大到小排序,asc是从小到大排序。
select * from tbl_1 order by mdate desc,mtime desc
将tbl_1整个表的数据按先mdate降序排序,再按mtime字段排序。
(2)、也可以结合where语句,如:select * from tbl_1 where itemcode= '15001' order by mdate desc,mtime desc
将itemcode为15001的查询出来,再按mdate,mtime 进行排序。 -
distinct语句
(1)去重语句,并且定要放在句头。
select distinct status from tbl_1
,对status进行去重,结果为OK,NG,(null) 。(空值也会出来)
(2)distinct不要使用在数据很大的表内,distinct会遍历需要去重的列,会导致sql的查询速度很慢。 -
lag()函数
(1)oracle中如果要取上一条记录可以使用lag()这个函数。
(2)用法:lag(字段,参数2)
字段:取前一条数据的字段。参数2:取前第几条数据。
例: select itemcode,lag(mdate,1) from tbl_1
取mdate上一条的数据。
itemcode | mdate |
---|---|
15001 | |
15001 | 20190815 |
15002 | 20190815 |
2233 | 20190810 |
(3)lag(字段,参数2,参数3)
如果字段没有上一条记录时,就返回参数3,如果没有参数3就返回空。
例:select itemcode,lag(mdate,1,'20190101') from tbl_1
itemcode | mdate |
---|---|
15001 | 20190101 |
15001 | 20190815 |
15002 | 20190815 |
2233 | 20190810 |
(4)lag可以搭配over使用。为上一条数据添加一些条件。
lag(字段,参数2,参数3)over (order by 字段1)
可以使用over里加入order by来排序,决定返回的字段上一条数据。
lag(字段,参数2,参数3)over(partition by 字段1 order by 字段1,字段2)
partition by是用来做区分用的。
例:select itemcode,lag(mdate,1) over(partition by itemcode order by itemcode)
itemcode | mdate |
---|---|
15001 | |
15001 | 20190815 |
15002 | |
2233 |
这样用partition by 对itemcode做区分就可以以itemcode查找上一条记录。
- avg()函数
在oracle中,我们可以用avg来求得某一个字段的平均数。select avg(col_1) from tbl_1
如果需要参照某一列字段来求得平均数,可以借助group by 语句。select col_2,avg(col_1) from tbl_1 group by col_2