日期:2014-05-16  浏览次数:20729 次

常用日期查询汇总
1.求当年天数的sql语句
SELECT ADD_MONTHS(TRUNC(SYSDATE, 'YYYY'), 12) - TRUNC(SYSDATE, 'YYYY') days FROM DUAL
2.求当月天数的sql语句
select to_number(add_months(trunc(sysdate, 'mm'), 1) - trunc(sysdate, 'mm'))   from dual;
 
3,生成当年的所有月份
 select TRUNC(SYSDATE, 'mm') + (rownum - 1)
  from dual
connect by rownum <= (SELECT ADD_MONTHS(TRUNC(SYSDATE, 'YYYY'), 12) -
                             TRUNC(SYSDATE, 'YYYY') days
                        FROM DUAL);
4, 获取每天的24个小时

select TRUNC(SYSDATE, 'dd') + (rownum - 1) / 24
  from dual
connect by rownum <= 24;

select to_char(sysdate + (rownum - 1) / 24, 'hh24')
  from dual
connect by rownum <= 24;

5, 获取每年的月份

 Select  add_months(trunc(sysdate, 'yyyy') ,Rownum - 1)
    from dual
connect by rownum < 13;

6, 获取每月的天数

Select trunc(sysdate, 'mm') + Rownum - 1
  from dual
connect by rownum < = (select to_number(add_months(trunc(sysdate, 'mm'), 1) -
                                        trunc(sysdate, 'mm'))
                         from dual)

 

 

--本周

select trunc(sysdate, 'd') + 1 from dual;

select trunc(sysdate, 'd') + 7 from dual;

--本月

select trunc(sysdate, 'mm') from dual;

select last_day(trunc(sysdate)) from dual;

--本季

select trunc(sysdate, 'Q') from dual;

select add_months(trunc(sysdate, 'Q'), 3) - 1 from dual;

--本年

select trunc(sysdate, 'yyyy') from dual;

select add_months(trunc(sysdate, 'yyyy'), 12) - 1 from dual;

-- 获取上月的开始时间和结束时间

select to_char(to_date(to_char(add_months(sysdate, -1), 'yyyy-mm'),'yyyy-mm'),'yyyy-mm-dd hh24:mi:ss')

  from dual;

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

  from dual;

-- 获取前一天的开始时间和结束时间

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

  from dual;

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

  from dual;

-- 获取上一个小时的开始时间和结束时间

select to_date(to_char(sysdate, 'yyyy-mm-dd') || (to_char(sysdate, 'hh24') - 1),'yyyy-mm-dd hh24')

  from dual;

select to_date(to_char(sysdate, 'yyyy-mm-dd') || (to_char(sysdate, 'hh24')),'yyyy-mm-dd hh24')

  from dual;