(Oracle10g)SQL语言基础-常用系统函数

上一篇 / 下一篇  2011-09-04 10:36:55 / 个人分类:Oracle

oracle常用的系统函数有以下5种:
 (1)字符:length、ltrim、rtrim、trim、substr
 (2)日期:sysdate、current_date,next_day
 (3)转换:to_char、to_date、to_number
 (4)聚集函数:sum、avg、max、min、count
 (5) 其他:user、decode、nvl
例子:
(1)字符
length:
select length('abcdef') from dual;//查询字符abcdef的长度,结果为6
select length('abc好ef') from dual;//查询字符abc好ef的长度,结果为6
注意:因为oracle当中使用的是16位的unicode编码,而一个汉字占用两个字节,正好是16位,所以在oracle当中一个汉字字符与一个英文字符的字符长度是一样的。
select lengthb('abc好ef') from dual;//查询字符abc好ef的字节长度,结果为7
ltrim:
select ltrim(' abcdef') from dual;//表示把oracle字符当中左边的空格截掉
rtrim:
select rtrim('abcdef ') from dual;//表示把oracle字符当中右边的空格截掉
trim:
select trim(‘ abcdef ')from dual;//表示把oracle字符当中左右两边的空格截掉
substr:
select substr('abcdef',2,3) from dual;//从第二个位置开始取3个字符串,结果为bcd
select substr('abcdef',1,3) from dual;//实现oracle左取串,结果为abc
select substr('abcdef',length('abcdef')-3+1,3) from dual;//实现oracle右取串,结果为def
(2)日期
sysdate:
select sysdate from dual;//oracle当中sysdate表示当前时间
current_date:
select current_date from dual;//和sysdate功能一样,不过current_date支持时间的格式化
alter session set NLS_DATE_FORMAT='dd-mon-yyyy hh:mi:ss';//格式化时间显示的格式
select next_day(sysdate,'星期三') from dual;//表示给定一个星期几是几号,如果还没到你指定的星期,比如说今天是星期一,你要知道星期三是几号,指的是这个即将到来的星期三;如果今天是星期四,你要知道星期三是几号,指的是下个即将到来的星期三。
 (3)转换
to_char:
select to_char(sysdate,'yyyy-mm-dd')from dual;//将日期显示转换成指定的字符形式
select to_char(sysdate,'yyyy-mm-dd hh:mi:ss') from dual;//默认的时间显示是12进制的
select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual;//将时间的显示转换成24进制的
to_date:
select to_date('12-3月-04')from dual;
to_number:
select to_number('333')from dual;//注意:只能将整数型的数字转换
(4)聚集函数
max:
select max(price) from books;//查询books表中书本价格最贵的
min:
select min(price) from books;//查询books表中书本价格最便宜的
sum :
select sum(price*qty) from books;//查询books表中书本总的价格,注:price代表单本书价格,qty代表数量
avg:
select avg(price) from books;//查询books表中书本的平均价格
count:
select count(price) from books;//查询pirce字段的所有值
select count(*)from books;//查询books表中所有的记录值
注意:这两个查询语句在很多情况下显示的结果是一样的,但是当pirce字段允许有null的情况下,查询字段的行数和查询记录的行数是不一样的。
(5)其他
user:
select user from dual;//查询当前的登录帐号
decode:
当我们要统计一个表中男生人数与女生人数的个数的时候,就会用到decode
select sum(decode(sex,'男',1,0)) 男人数,sum(decode(sex,'女',1,0)) from p;
//统计表p中sex字段中男与女的个数,sex(字段)、‘男’(字段的值) 、1(是男的用1表示),0(不是男的用0表示).
nvl:
比如说我们表books中字段price当中有null值存在,我们需要用一个指定的标签来把null的值显示出来。
select bname,nvl(price,'空值')from books;
null&not null:
select * from books where price is null;//显示pirce当中有null值的记录
select * from books where price is not null;//显示pirce当中没有null值得记录
asc(升序)&desc(降序):
select * from books order by price asc;//按照price字段升序排列
select * from books order by price desc;//按照price字段降序排列
select distinct a1 from aa;//让a1字段当中的重复数据只显示一条

TAG:

 

评分:0

我来说两句

Open Toolbar