第十二天 单行函数及其他函数

order by 排序:
默认是升序,desc是降序。

ps:排序时 

如果数字是字符串,则 12<3,字符串都是左对齐
如果数字仅代表数字,则 12>3 数字都是右对齐

时间的比较,看成时间轴 越左边的越小,右边的大。

排序时 可以写 order by 2 就是select所查字段的第二列
也可以写 order by 别名。

函数:

概念:输入 -- 运算 -- 输出 就是函数。

 根据输入的不同 又分为单行函数和多行函数。

常用函数:

Upper函数    //将返回的字符变为大写

Lower函数    //将返回的字符变为小写

Length函数   //返回字符的长度 King , 返回4

 Trunc函数  //截取数字 

SELECT TRUNC(15.79,1) "Truncate" FROM DUAL; 15.7 

months_between       //求一段时间内有几个月

例    SQL> select trunc(months_between(sysdate,hire_date), 0) from employees;  //查询员工从入职到现在共几个月 用trunc函数取整

SQL> select sysdate+3650 from dual;    //10年之后的日期

 SQL> select add_months(sysdate, 120) from dual;    //用月份表示10年后

SQL> select next_day('2015-09-01', 'friday') from dual;     //9.01往后的第一个周五

SQL> select last_day(sysdate) from dual; last_day 这个月的最后一天

select next_day(last_day('2017-06-01'),'sunday') from dual; //先用last_day找到月底,再用next_day找到7月的第一个周日

Extractyear from hire_date=2006     //抽取2006年,也可以抽取月份。

yminterval      dsinterval     //   ??

 类型转换和其他函数:

SQL> select to_char(salary, '$999,999.00') from employees;    //把数值转换成字符

SQL> select last_name, to_char(hire_date, 'dd-Mon-RR') from employees;  //把日期转换成其他格式输出

SQL> select to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') from dual;//把日期转换成其他格式输出

 

 

练习:

查询2006年入职员工:

 select last_name

from employees

where extract(year from hire_date)=2006; 

查询历年9月份入职的员工:

select last_name

from employees

where extract(month from hire_date)=9;

 其他函数:

nvl:

nvl(val1, val2)

if val1 is not null

then

    return val1;

else

例select last_name,nvl(to_char(department_id),'N/A') from employees;

case job_id

  when 'IT_PROG' then salary+1000

  when 'SA_REP' then salary+1500

  when 'ST_CLERK' then salary+2000

  else salary

end new_salary

from employees;

 

 

 

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/zxk666/p/7252089.html