sql函数

单行函数对于从表中查询的每一行只返回一个值

可以出现在 SELECT 子句中和 WHERE 子句中

单行函数可以大致划分为:

数字函数

字符函数

日期函数

转换函数

其他函数

--

 

round(sal) 四舍五入到个位

 

工资四舍五入到小数点后一位

--》select round(sal,-1) from teacher 

 

 sal工资 tid (number(18))身份证(有15和18位的)

substr()字符截取   trim()去空格

substr(tid,1,2)和substr(tid,0,2)都是截取前两位

substr(tid,1)截取到最后

length(tid) 注意这里不管tid实际是15还是18位,length都为18

所以需要 trim(tid)去掉空格

--》select substr(tid,1,2),substr(tid,0,2),substr(tid,1),length(trim(tid)) from teacher

 

日期类型  也是 按数值类型存储的

--》select sysdate+1,sysdate+1/4 from dual 日期加1天,和日期加6小时

 

to_number 字符转换成数值(按指定格式)

to_char 把其他转换成字符(按指定格式)

to_date 将字符转换成日期(按指定格式)

示例

--》select to_number('123'),

to_char(1234,'99,99'),

to_date('1992-03-23','yyyy-mm-dd'),

to_char(sysdate,'yyyy-mm-dd hh24:mi:ss')

from dual

 

nvl(列,显示什么)      如果列为空,将显示什么

nvl2(列,有值显示怎么显示,为空显示什么)     如果列,不为空显示什么(可以用函数改变值),为空将显示什么

decode(列,列为null,显示0,列为a,列为a显示b,其余显示c)

示例

--》select t.sal,t.comm.

(t.sal + nvl(t.comm,0)) gz,

(t.sal + nvl2(t.comm,t.comm + 1000,0)) gz1,

(t.sal + decode(t.comm,null,0,2300,2500,t.comm)) gz3

from teacher

 

 

-----

聚合函数基于一组行来返回结果

为每一组行返回一个值

    聚合函数:

avg  

min

max

sum

count

--

GROUP BY子句

--

用于将信息划分为更小的组

每一组行返回针对该组的单个结果

--

HAVING子句

--

用于指定 GROUP BY 子句检索行的条件

having后面 只能接聚合函数

示例:查询部门员工超过10人以上的数据

-->  select deptno,sum(sal),avg(sal)

from teacher 

group by deptno

having count(*)>10    不能再加上 -- and sal > 1000

-------------

 分析函数    用来做排名,也可以用来做分页

以下三个分析函数用于计算一个行在一组有序行

中的排位,序号从1开始

  ROW_NUMBER 返回连续的排位,不论值是否相等

  RANK 具有相等值的行排位相同,序数随后跳跃

  DENSE_RANK 具有相等值的行排位相同,序号是连续的

示例:

--》 select tname,deptno,

rank() over(partition by deptno order by sal) rank_1,

dense_rank over(partition by deptno order by sal) dense_rank,

row_number over(partition by deptno order by sal) row_number

from teacher

----

联合查询

集合操作符将两个查询的结果组合成一个结果

union / union all          返回各个查询的所有记录

intersect          返回两个查询的共有记录

minus             返回第一个查询检索出的记录减去第二个查询检索出的记录之后剩余的记录

猜你喜欢

转载自4636.iteye.com/blog/2356550