本文包含一些与日期相关的常见查询。
希望用户发现它有用。
=========================
1.确定一个月中特定工作日的第一次和最后一次发生的日期
------------------------------------
Select next_day(trunc(sysdate,'mm')-1,'SUNDAY') First_Sunday, next_day(last_day(trunc(sysdate,'mm'))-7,'SUNDAY') Last_Sunday from dual
对于其他日子,请在查询中修改DAY的名称。
2.确定一个月的第一天和最后一天
-------------------------------------------------- ----------------------
select trunc(sysdate,'mm') Firstday,
last_day(sysdate) Lastday from dual
3从日期中提取时间单位
-------------------------------------------------- ----------
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
4.找出一年中的天数。
---------------------------------
select add_months(trunc(sysdate,'y'),12) - trunc(sysdate,'y') from dual
5.找出年份是否为a年。
-------------------------------------------------- -------------------
select decode(to_char(last_day(add_months(trunc(sysdate,'y'),1)),'DD'),28 ,'Not a Leap Year','Leap Year') from dual
6.列出年度的季度开始和结束日期
-------------------------------------------------- -----------------------
Select rownum qtr,
add_months(trunc(sysdate,'y'),(rownum-1)*3) q_start, add_months(trunc(sysdate,'y'),rownum*3)-1 q_end from emp where rownum <= 4
7,从表中检索三个最新日期
================================
select e.hiredate from
(
select dense_rank() over (order by hiredate desc)n,hiredate
from emp )e where e.n<=3
8.确定两个日期之间的月数或年数
-------------------------------------------------- -------------------------------------------------
select months_between(max_hd,min_hd) MONTHS,
months_between(max_hd,min_hd)/12 YEARS
from (select min(hiredate) min_hd, max(hiredate) max_hd from emp ) x
9,确定两个日期之间的秒数,分钟数或小时数
-------------------------------------------------- -------------------------------------------------- --------------
select dy*24 as hr, dy*24*60 as min, dy*24*60*60 as sec from (select (max(case when ename = 'WARD' then hiredate end) -
max(case when ename = 'ALLEN' then hiredate end)) as dy from emp) x
10.确定当前记录和下一条记录之间的日期差
-------------------------------------------------- -------------------------------------------------- -------------
select ename, hiredate, next_hd,
next_hd - hiredate diff from (
select deptno, ename, hiredate, lead(hiredate)over(order by hiredate) next_hd
from emp) ORDER BY HIREDATE
11,计算一年中平日的发生次数
-------------------------------------------------- ------------------------------
with x as ( select level lvl from dual connect by level <= ( add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y'))
) select to_char(trunc(sysdate,'y')+lvl-1,'DAY'), count(*) from x group by to_char(trunc(sysdate,'y')+lvl-1,'DAY')
还要检查重要日期相关查询-2
From: https://bytes.com/topic/oracle/insights/739959-important-date-related-queries-1-a

被折叠的 条评论
为什么被折叠?



