原因
presto没有直接的日期转星期几的方式,但是可以通过函数mod,date_diff多种函数进行求模转换成我们想要的星期几。
SELECT case mod(
date_diff(
'day',
cast('2021-02-01' as date),
cast(
cast(stringtime_field_name as timestamp) as date)),
7)
when 0 then '周一'
when 1 then '周二'
when 2 then '周三'
when 3 then '周四'
when 4 then '周五'
when 5 then '周六'
when 6 then '周日'
end AS "星期几"
FROM "presto_ods"."thexing_ads_itm_analysis"
解析
1.stringtime_field_name 是表里面的字段,将其转换成时间戳。也可以是当前日期函数currentdate(),这样就不用转换变成如下:
SELECT case mod(
date_diff(
'day',
cast('2021-02-01' as date),
cast(
cast(CurrentDate() as date)),
7)
when 0 then '周一'
when 1 then '周二'
when 2 then '周三'
when 3 then '周四'
when 4 then '周五'
when 5 then '周六'
when 6 then '周日'
end AS "星期几"
FROM "presto_ods"."thexing_ads_itm_analysis"
在通过date_diff,计算date与一个为星期一的日期之间的天数间隔,mod计算间隔除7的余数
通过case把余数转为星期几。
常见的日期处理方式
本文总结一下Presto SQL日期时间比较常用的处理:
1. 特定的日期时间值
select
current_date,
current_time,
current_timestamp,
date'2021-09-01',
time'12:30:00',
timestamp'2021-09-01 12:30:00'
需要输入日期时间时,使用前缀date、timestamp、time就会将输入的字符串识别为日期时间。
2. 常用的日期时间处理
select
current_date,
current_date - interval '1' day,
current_date + interval '3' day,
date_add('day', -1, current_date),
date_add('day', 3, current_date),
date_trunc('month', current_date),
date_trunc('month', current_date) - interval '1' month,
date_trunc('month', current_date) - interval '1' day,
date_trunc('week', current_date),
date_diff('day', date'2021-09-01', date'2021-09-23'),
to_char(current_date, 'yyyy-mm'),
to_char(current_date, 'yyyymmdd'),
date(date_parse('20210901', '%Y%m%d')),
date('2021-09-01'),
cast('2021-09-01' as date)
拓展
mysql有获取自己的当期星期的函数,只需要case when 转换一下值就行
DAYNAME():返回对应周几的英文名
DAYOFWEEK():对应周几的引索(1=周日,2=周一。。。。7=周六)
WEEKDAY():对应周几的引索(0=周一,1=周二。。。。6=周日)
SELECT
WEEKDAY(CURRENT_DATE),
DAYOFWEEK(CURRENT_DATE),
case mod(
datediff('2021-02-01',CURRENT_DATE),7)
WHEN 0 THEN '周一'
WHEN 1 THEN '周二'
WHEN 2 THEN '周三'
WHEN 3 THEN '周四'
WHEN 4 THEN '周五'
WHEN 5 THEN '周六'
WHEN 6 THEN '周日'
end '周几'
FROM "hive_eda_ads_itm_okr_analysis"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)