MySQL时间差

时间差函数在SQL中很常见,然而不同的数据库时间函数有些差别,下面简单比对下。

时间差函数:timestampdiff

MySQL

      语法:  timestampdiff(unit,begin,end)

       begin和end可以为DATE或DATETIME类型,并且可允许参数为混合类型。

DB2

      语法:timestampdiff(unit,char(begin-end))

begin和end需要为时间戳格式。若非时间戳类型,用timestamp()函数转换。

   timestampdiff(unit,char(timestamp(begin)-timestamp(end)))

 unit参数是确定(end-begin)时间差的单位

单位 MySQL(UNIT) DB2(UNIT)
毫秒   1
second 2
分钟 minute 4
小时 hour 8
day 16
week 32
month 64
quarter 128
year 256

例子:计算一个人的年龄:

MySql:

select  timestampdiff(year,CURRENT_DATE,BIRTH_DT) 

DB2:

select  timestampdiff(256,char(CURRENT_DATE - BIRTH_DT)) 

HIVE:(hive没有timstampdiff函数,因而可以根据年份相减进行计算)

1.select  if(datediff(current_date,concat(substr(CURRENT_DATE,0,4),substr(BIRTH_DT,5,7)))>=0,

                (substr(CURRENT_DATE,0,4)-SUBSTR(BIRTH_DT,0,4)),

                (substr(CURRENT_DATE,0,4)-SUBSTR(BIRTH_DT,0,4)-1)) 

2.select  if(datediff(current_date,concat(substr(CURRENT_DATE,0,4),substr(BIRTH_DT,5,7)))>=0,

                (year(CURRENT_DATE)-year(BIRTH_DT)),

                (year(CURRENT_DATE)-year(BIRTH_DT)-1)) 

发布了79 篇原创文章 · 获赞 0 · 访问量 2849

猜你喜欢

转载自blog.csdn.net/administratorrrr/article/details/103697786