SQL (HUE) :有什么方法可以将 24 小时时间转换为 12 小时 AM / PM 格式的小时桶

SQL (HUE) : Is there any way to convert 24 hrs time into 12 hrs AM / PM format with hours buckets

我有 table A​​,其中包含存储为时间戳数据类型的列 time

Table A:包含 HH:MM:SS 中的时间列,采用 24 小时格式。

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得到小时。
然后根据小时设置AM/PM。
lpad 用于确保您获得 01 AM 格式的数据。