问题描述
我有表 A,其中包含存储为时间戳数据类型的列 time。
表 A:包含 24 小时格式的 HH:MM:SS 时间列。
Sample data below:
time
12:32:45
16:09:04
09:02:16
18:34:33
08:59:30
Now I want to create a bucket based on hours and adding AM/PM.
eg:
time between 00:00:00 - 00:59:00 = 12 AM,01:00:00 - 01:59:00 = 01 AM,14:00:00 - 14:59:00 = 02 PM and so on.
Desired Output :
time new_time
12:32:45 12 PM
16:09:04 04 PM
09:02:16 09 AM
18:34:33 06 PM
08:59:30 08 AM
解决方法
请使用以下代码。对于您的查询,将 now()
替换为 time
。
SELECT now(),lpad(CONCAT (
CAST (extract(hour from now()) + CASE WHEN extract(hour from now()) >12 THEN -12
WHEN extract(hour from now())=0 THEN 12
ELSE 0 END AS string),CASE WHEN extract(hour from now()) >=12 THEN ' PM' ELSE ' AM' END),5,'0') as new_time
说明——
首先我检查小时是否> 12。如果是,减去12得到小时。
然后根据小时设置上午/下午。
lpad 用于确保您以 01 AM 格式获取数据。