Home  >  Article  >  Database  >  Oracle 关于日期格式转换与使用

Oracle 关于日期格式转换与使用

WBOY
WBOYOriginal
2016-06-07 17:30:341057browse

在oracle中我们经常会和日期打交道,在做报表的时候经常会用日报,周报,月报之类的条件进行分组;

在Oracle中我们经常会和日期打交道,在做报表的时候经常会用日报,周报,月报之类的条件进行分组;

我写了些例子来启发下大脑         
         
select Sysdate from dual
select to_char(sysdate,'yyyy') as 年 from dual
select to_char(sysdate,'mm') as 月 from dual
select to_char(sysdate,'dd') as 日 from dual
select to_char(sysdate,'iw') as 周一到周日为一周 from dual
select to_char(sysdate,'ww') as 一月一日加6为一周类推 from dual
select to_char(sysdate,'HH24:mi:ss') as 时分秒 from dual


--根据年分组
select to_char(sysdate,'yyyy') as 年 from dual
--根据月分组
select to_char(sysdate,'yyyy-mm') as 年 from dual
--根据天分组
select to_char(sysdate,'yyyy-mm-dd') as 年 from dual
--根据周分组
select to_char(sysdate,'yyyy-iw') as 年 from dual
select to_char(sysdate,'yyyy-ww') as 年 from dual

注意:

按照周进行分组会出现问题:如:2012年12月31日 是周一所以就会归结到2013年的第一周中,iw查询出来的结果是01但是yyyy对应的是还2012所以就和2012年一月的第一周无法区分开。

方法二:

查询出指定日期所在周的开始结束的时间:

--规定每周是从周一开始,周末结束
select next_day(sysdate,2)-7 from dual --得到周一
select next_day(sysdate,1) from dual --得到周末


next_day()  获取下一个周日(1),一(2),二(3),三(4),四(5),,五(6),六(7)

用中文也是可以的:

--规定每周是从周一开始,周末结束
select next_day(sysdate,'星期一')-7 from dual --得到周一
select next_day(sysdate,'星期日') from dual --得到周末

得到日期范围后将这个范围拼接在一起进行分组就可以了

--根据省份分组,省份列种包含市(福建福州,黑龙江牡丹江)
/*
思路:1.先用substr(列明,开始位置第一个为1,截取字数)来切割省份列
      2.截取后黑龙江变成黑龙后要恢复回来 
      case 
      when substr(列名,1,2) like '黑龙' then '黑龙江'
      when substr(列名,1,2) like '内蒙' then '内蒙古'
      else
      to_char(substr(列明,1,2))
      end
*/

linux

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn