0%

SQL | 时间处理 Time

SQL时间相关处理~

基本语法

YEAR():取日期中的年份

1
2
year('2021-12-31')
-- 2021

去年同一天:

1
add_months(current_date, -12)

MONTH():取日期中的月份

当月第一天:

1
date_format(current_date, 'yyyy-MM-01')

当月最后一天:

1
2
-- date 可以为yyyyMMdd或yyyy-MM-dd
last_day(current_day)

上个月末(上个月最后一天):

1
2
date_sub(date_format(current_date, 'yyyy-MM-01'), 1)
last_day(add_months(date, -1))

上个月同一天:

1
add_months(current_date, -1)

$n$个月前同一天:

1
add_months(current_date, -n)

月调度任务(仅每月最后一天有数),取最近有数一个分区:

1
2
3
4
5
6
where 
(
case when '${date}' = last_day('${date}') and date = '${date}' then 1
when '${date}' < last_day('${date}') and date = last_day(add_months('${date}', -1)) then 1
else 0 end
) = 1

WEEKOFYEAR(STRING date):返回时间字符出位于一年中的第几周内

1
2
weekofyear('2016-12-08 10:05:15')
-- 49

周几/星期几:

1
2
3
4
5
6
case    when cast(pmod(datediff(pt, '1900-01-07'), 7) as int) = 0 then 7 
else cast(pmod(datediff(pt, '1900-01-07'), 7)
end as weekdays
-- cast(pmod(datediff(pt, '1900-01-07'), 7)取值范围0-6
-- 或
cast(date_format(pt, 'u') as int) -- 取值范围1-7

当周的周一:

1
date_sub(current_date, cast(date_format(current_date, 'u') as int) - 1)

最近一个周日:

1
date_sub(current_date, cast(date_format(current_date, 'u') as int))

格式转换

日期 to 日期

yyyy/MM/dd格式的日期转换为yyyy-MM-dd格式:

1
concat_ws('-', split(date, '/')[0], lpad(split(date, '/')[1], 2, '0'), lpad(split(date, '/')[2], 2, '0'))

yyyyMMdd格式转换为yyyy-MM-dd格式:

1
2
3
date_sub(date, 0)
date_add(date, 0)
from_unixtime(unix_timestamp(date, 'yyyyMMdd'), 'yyyy-MM-dd')

日期 to 时间戳

时间戳 to 日期

10位时间戳(bigint格式,单位秒)转yyyyMMdd

1
from_unixtime(ts, 'yyyyMMdd')

10位时间戳(bigint格式,单位秒)转yyyy-MM-ddyyyy-MM-dd HH:mm:ss

1
2
from_unixtime(ts, 'yyyy-MM-dd')
from_unixtime(ts, 'yyyy-MM-dd HH:mm:ss')

13位时间戳(单位毫秒)转yyyyMMdd

1
from_unixtime(ts / 1000, 'yyyyMMdd')

1毫秒 = $\frac{1}{1000}$ 秒

1

1

参考资料

Thank you for your approval.

欢迎关注我的其它发布渠道