
1.判断闰年
使用LAST_DAY找出2月的最后一天:
select to_char(last_day(add_months(trunc(sysdate,'y'),1)),'DD') from dual;
2.从给定日期里提取年月日时分秒
select to_number(to_char(sysdate,'hh24')) hour,
to_number(to_char(sysdate,'mi')) min,
to_number(to_char(sysdate,'ss')) sec,
to_number(to_char(sysdate,'dd')) day,
to_number(to_char(sysdate,'mm')) mth,
to_number(to_char(sysdate,'yyyy')) year
from dual;
3.计算一个月的第一天和最后一天
使用TRUNC函数找出当月第一天,并使用LAST_DAY函数找出当月最后一天:
select trunc(sysdate,'mm') firstdat,
last_day(sysdate) lastday
from dual;
4.列出一年中的所有星期五
使用CONNECT BY递归查询当前年份的每一天,然后调用TO_CHAR函数筛选出星期五对应的日期:
with x as (
select trunc(sysdate,'y')+level-1 dy
from dual connect by level<=add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y')
)
select * from x where to_char(dy,'dy')='星期五';
5.找出当前月份第一个和最后一个星期一
使用NEXT_DAY和LAST_DAY加上一些日期计算技巧:
select next_day(trunc(sysdate,'mm')-1,'星期一') first_monday,
next_day(last_day(trunc(sysdate,'mm'))-7,'星期一') last_monday
from dual;
NEXT_DAY的第二个参数可用数字代替星期几,如1代表星期日,2代表星期一
6.生成日历
使用CONNECT BY递归查询当月每一天,再分别拿出当月每一天对应当年的第几周(wk),每一天是星期几(dw),
当前月份(curr_mth),然后递增dm值,直至月末,最后使用CASE表达式来决定每一天对应的是星期几,对结果
按照wk组、排序,如下:
with x as (
select * from (select to_char(trunc(sysdate,'mm')+level-1,'iw') wk,
to_char(trunc(sysdate,'mm')+level-1,'dd') dm,
to_number(to_char(trunc(sysdate,'mm')+level-1,'d')) dw,
to_char(trunc(sysdate,'mm')+level-1,'mm') curr_mth,
to_char(sysdate,'mm') mth
from dual connect by level<=31)
where curr_mth=mth
)
select max(case dw when 2 then dm end) Mo,
max(case dw when 3 then dm end) Tu,
max(case dw when 4 then dm end) We,
max(case dw when 5 then dm end) Th,
max(case dw when 6 then dm end) Fr,
max(case dw when 7 then dm end) Sa,
max(case dw when 1 then dm end) Su
from x group by wk order by wk;
7.依据特定时间单位检索数据
依据指定的月份、星期或其他时间来筛选记录行:
select emp_name from emp
where rtrim(to_char(create_time,'month')) in ('february','december')
or rtrim(to_char(create_time,'day'))='tuesday';
整理自《SQL经典实例》
网友评论