sql 语句系列(两个日期之间)[八百章之第十七章]

前言

进入了日期章了。

年月日加减法

分别对原有的日期进行加减法。

sql server

select DATEADD(DAY,-5,HIREDATE) as hd_mimus_5D,
DATEADD(DAY,5,HIREDATE) as hd_plus_5D,
DATEADD(MONTH,-5,HIREDATE) as hd_minus_5M,
DATEDIFF(MONTH,5,HIREDATE) as hd_pulus_5M,
DATEADD(YEAR,-5,HIREDATE) as hd_minus_5Y,
DATEDIFF(YEAR,5,HIREDATE) as hd_pulus_5Y
from emp
where DEPTNO=20

mysql

select HIREDATE -INTERVAL 5 DAY as hd_mimus_5D,
HIREDATE + INTERVAL 5 DAY as hd_plus_5D,
HIREDATE -INTERVAL 5 MONTH as hd_minus_5M,
HIREDATE +INTERVAL 5 MONTH as hd_pulus_5M,
HIREDATE -INTERVAL 5 YEAR as hd_minus_5Y,
HIREDATE +INTERVAL 5 YEAR as hd_pulus_5Y
from emp
where DEPTNO=20

计算两个日期之间的天数

sql server 与 mysql

select DATEDIFF(DAY,word_hd,allen_hd)
from (
select HIREDATE as word_hd
from EMP
where ENAME='WARD'
)x,
(select  HIREDATE as allen_hd
from EMP
where ENAME='ALLEN'
) y

在此只是为了介绍一下DATEDIFF函数可以计算两个日期的相差的间隔。

两个日期之间的工作日的天数

1.我们要知道两个日期区间是什么。比如说2月6号到2月23号,那么我们就要得出2月6号到2月23这个区间出来。

2.我们得出区间,那么我们需要遍历区间,然后判断那一天是工作日。

3.我们应该知道工作日是星期一到星期五。

mysql:

select sum(CASE when DATE_FORMAT(DATE_ADD(jones_hd,INTERVAL T100.ID-1 DAY),'%a') in ('Sat','Sun') then 0 else 1 END) as days
from
(select
MAX(case when ename='BLAKE' then HIREDATE end) as blake_hd,
MAX(case when ename='JONES' then HIREDATE end) as jones_hd
from EMP
where ename in ('BLAKE','JONES')
) x,T100
where T100.ID<=DATEDIFF(x.blake_hd,x.jones_hd)+1

看起来有一丢丢复杂,其实不然。

有两个地方你无需关注。

(select
MAX(case when ename='BLAKE' then HIREDATE end) as blake_hd,
MAX(case when ename='JONES' then HIREDATE end) as jones_hd
from EMP
where ename in ('BLAKE','JONES')
)

这一段仅仅是为了得出两个日期,也就是业务。其余部分才是功能。
如果你阅读了前面的章节,那么你仅仅需要关注的是DATE_FORMAT 函数。

sql server

select sum(CASE when 
datename(DW,DATEADD(DAY,T100.ID-1,jones_hd)) in ('星期六','星期天') then 0 else 1 END) as days
from
(select
MAX(case when ename='BLAKE' then HIREDATE end) as blake_hd,
MAX(case when ename='JONES' then HIREDATE end) as jones_hd
from EMP
where ename in ('BLAKE','JONES')
) x,T100
where T100.ID<=DATEDIFF(DAY,x.jones_hd,x.blake_hd)+1

可能有人觉得我这里写星期六星期天奇怪哈,那是因为我自己的电脑装的是中文版。英文版是 in ('SATURDATA','SUNDAY')。
知识点:datename函数

计算两个日期之间相差的月份和年份

mysql:

select x.mounths as ms,x.mounths/12 as ys from
(select ((YEAR(max_hir)-YEAR(min_hir))*12+(MONTH(max_hir)-MONTH(min_hir))) as mounths from 
(select MIN(HIREDATE) as min_hir,MAX(HIREDATE) AS max_hir
FROM EMP) e
)x

sql server

select DATEDIFF(MONTH,e.min_hir,e.max_hir) as ms,CAST(DATEDIFF(MONTH,e.max_hir,e.min_hir) as decimal )/12  from
(select MIN(HIREDATE) as min_hir,MAX(HIREDATE) AS max_hir
FROM EMP
) e

注:在做除法的时候一定要转换一下数据类型。

计算两个日期之间相差的秒数、分钟数、小时数

mysql 和 sqlserver 通用

select DATEDIFF(day,e.min_hir,e.max_hir)*12 as hrs,DATEDIFF(day,e.min_hir,e.max_hir)*12*60 as mins,DATEDIFF(day,e.min_hir,e.max_hir)*12*60*60 as sec   from
(select MIN(HIREDATE) as min_hir,MAX(HIREDATE) AS max_hir
FROM EMP
) e

你可能感兴趣的:(sql 语句系列(两个日期之间)[八百章之第十七章])