时间处理
将字符串转换为日期;
注意:
1、小时用的是mi而不是mm,否则无效
2、字符串的日期格式要跟第二个参数的日期格式一致
3、得到的结果是yyyy-mm-dd hh24:mi:ss这种格式的日期
to_timestamp(timeStr,'yyyy-mm-dd hh24:mi:ss') --timeStr是字符串
--例:
select to_timestamp('20210623','yyyymmdd') from dual;
--输出结果:2021-06-23 00:00:00
将日期转换为字符串
用to_date方法获取的日期是yyyy-mm-dd格式,可能是数据库版本差异吧,具体没有验证。
to_char(date,'yyyymmdd') --date为日期类型,第二个参数为期望的格式
--例:
select to_char(sysdate,'yyyymmdd') from dual;
--输出结果:20210623
获取日期的年月日时分秒
to_char(time,'hh') --time需要时日期类型
获取指定月份的最后一天
last_day(to_date('2021-06-01','YYYY-MM-DD'))
--输出:2021-06-30
获取指定月份的天数
to_char(last_day(to_date('2021-02-01','YYYY-MM-DD')),'DD')
--输出:28
加减指定月份数
add_months(sysdate,m)
--例:
add_months(to_timestamp('20210923','yyyymmdd'),-3)
--输出:2021-06-23
--注意格式变化
字符串拼接
使用||符号进行拼接
select a||b from table
多行合并一行
select
a
,b
,strcat(c) over(partition by a,b order by c) as c
from table group by 1,2
行转列
select
statis_date
,a
,b
,max(
case
when substring(statis_date,7,2) = '01'
then d
else 0
end
) as 'first_cancel'
,max(
case
when substring(statis_date,7,2) = '02'
then d
else 0
end
) as 'second_cancel'
,max(
case
when substring(statis_date,7,2) = '03'
then d
else 0
end
) as 'third_cancel'
from table
字符串
截取
substr(str,开始位置,截取长度)
--开始位置从1开始,0和1效果一样
按规则切割成数组
regexp_substr(String, pattern, position, occurrence, modifier)
参数说明:
string:需要进行正则处理的字符串
pattern:进行匹配的正则表达式
position:起始位置,从字符串的第几个字符开始正则表达式匹配(默认为1) 注意:字符串最初的位置是1而不是0
occurrence:获取第几个分割出来的组(分割后最初的字符串会按分割的顺序排列成组)
modifier:模式(‘i’不区分大小写进行检索;‘c’区分大小写进行检索。默认为’c’)针对的是正则表达式里字符大小写的匹配
排序
row_number() over(partition by statis_date,caller_no order by call_begin desc) as rn
排序函数:row_number()
over:根据什么字段进行排序
partition by 根据什么字段进行分组,可多个字段分组
字符转义
translate(string,from_str,to_str);
类似正则表达式的简易写法,string为待转义字符串,from_str定义需要转义的字符,to_str定义要转义成什么字符,from_str与to_str定义的字符一一对应。可灵活运用。
例:
eg1:
#将0-9的数字一一转换成对应的a-j字母
translate('119','0123456789','abcdefghij')
#结果:bbj
eg2:
#将所有数字都转换成9
translate('119','0123456789','9999999999')
#结果:999