Oracle常用函数及SQL

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40426638/article/details/85678584

一:group by可以根据给定数据列的每个成员对查询结果进行分组统计,最终得到一个汇总表 
select字句中的列名必须为分组列或列函数.列函数对于group by字句定义的每个组返回一个结果 
group by一般和聚合函数一使用才有意义,比如count,sum,avg等,使用group by 的两个要素: 

(1)出现在select后面的字段,要么是聚合函数中的,要么是group by中的.(如果不这样,oracle不知道怎么分组)
(2)要筛选结果,可以先使用where再用group by或者先用group by再用having

二:dbms_output用法(一般使用在存储过程或者存储函数调试的时候)

set serveroutput on;

begin

 
dbms_output.put('a'); --写入buffer但不输出

  
dbms_output.new_line; --回车(换行),输出     

  
dbms_output.put_line('hello world!'); --输出并换行 

end;

三:字符串拼接

select concat('AB','CD') 字符拼接 from dual;

select 'AB'||'CD' 字符拼接 from dual;

两种结果都是ABCD

四:四舍五入函数和截取函数

select round(100.567,2) from dual

结果100.57

select trunc(100.567) from dual

结果100

两个函数,如果都不写位数,都是取整

比如:如果select trunc(100.567,2) from dual结果就是100.56

五,空值处理函数

比如:select NVL(NULL,0) from dual  表示为空时返回0

NVL(检测的值,如果为null 的值);

NVL2(检测的值,如果不为null 的值,如果为null 的值);

六 :条件取值decode函数

decode(条件,值1,翻译值1,值2,翻译值2,...值n,翻译值n,缺省值)

select name,decode( classid,1,' 一班',2,' 二班
',3,'三班') as 类型from t_student

也可以用case when 来实现

select name ,(case classid
when 1 then '一班'
when 2 then '二班'
when 3 then '三班'
else '其它'
end
) from t_student

还可以写成

select name,(case
when classid= 1 then '一班'
when classid= 2 then '二班'
when classid= 3 then '三班'
end ) from t_student

七,多个值写到一条记录函数 wmsys.wm_concat

select (select wmsys.wm_concat(to_char(student.name)) 学生名称
                                 from t_student student
                                where student.classid=class.id) 学生名称,class.name 班级名称 from t_class class

查出班级名称和班级下所有学生名称,并在班级记录里(相当于根据班级分组并且查询出班级姓名)

 listagg() WITHIN GROUP ()这个函数也行

八:根据某一列有规律字段排序

递归查询 connect by prior start with

https://www.cnblogs.com/benbenduo/p/4588612.html

九:cast (字段 as 类型) 函数

select  CAST( avg(zbjg.ZBJE) as DECIMAL(18,2)) zbje from xm_zbjg zbjg where zbjg.ZBJE>0

猜你喜欢

转载自blog.csdn.net/weixin_40426638/article/details/85678584
今日推荐