我正在使用一个完全混乱的数据库,需要找出解决它的最佳方法。现在我有时间进入这个表格,分为12小时和24小时格式(有些是01:30 PM,有些是13:30 PM)。为了将预定时间与实际时间进行正确比较,我需要采用标准化的24小时格式。
下面的示例表: 注意我无法进行任何永久性更改,因为我没有这些数据的权限。
Mary ran to the supermarket to get her grocerie(s) but she forgot her keys and coin(s)
现在我有:
Sched St Date Sched Time Actual Start Actual End
09/11/2017 00:00:00 11:30 AM 09/11/2017 11:34:16 09/11/2017 11:58:00
05/26/2017 00:00:00 03:30 PM 05/26/2017 15:40:00 05/26/2017 15:55:15
11/06/2017 00:00:00 19:30 PM 11/06/2017 21:25:00 11/06/2017 21:45:00
当我尝试连续获取全部时间(即07:00 PM)时,我收到了错误消息。任何人都可以用干净的方式帮我解决这个问题吗?
答案 0 :(得分:0)
我建议你将Sched_Time从VARCHAR转换为TIME。然后,您可以将Sched_Time规范化为24小时格式,并将其与Sched_St_Date组合以获取所需的TIMESTAMP字段。
CAST( SUBSTRING(Sched_Time FROM 0 FOR POSITION(' ' IN Sched_Time)) AS TIME ) AS NumericTime
这假设所有字段都有" "分隔器。根据您的数据有多糟糕,您可能会遇到CAST错误。只需不断添加逻辑来处理不同的条件。
CASE WHEN POSITION('AM' IN Sched_Time) > 0 THEN 'AM' WHEN POSITION('PM' IN Sched_Time) > 0 THEN 'PM' ELSE 'PM' -- Assume 'PM' if not specified (can change as needed) END AS TimeOfDay
CASE WHEN CAST(SUBSTRING(TRIM(Sched_Time) FROM 0 FOR 2) AS INTEGER) > 12 THEN NumericTime -- Already in 24-hour format ELSE CASE WHEN TimeOfDay = 'AM' THEN NumericTime -- Already suitable for 24-hour format ELSE NumericTime + INTERVAL '12' HOUR -- Convert 'PM' time to 24-hour format END END AS MyFinalTime
https://stackoverflow.com/a/47526411/8772888
CAST(Sched_St_Date AS DATE) + CAST(MyFinalTime AS INTERVAL HOUR TO MINUTE) AS Sched_St_Timestamp
SELECT CAST( SUBSTRING(Sched_Time FROM 0 FOR POSITION(' ' IN Sched_Time)) AS TIME ) AS NumericTime, CASE WHEN POSITION('AM' IN Sched_Time) > 0 THEN 'AM' WHEN POSITION('PM' IN Sched_Time) > 0 THEN 'PM' ELSE 'PM' -- Assume 'PM' if not specified (can change as needed) END AS TimeOfDay, CASE WHEN CAST(SUBSTRING(TRIM(Sched_Time) FROM 0 FOR 2) AS INTEGER) > 12 THEN NumericTime -- Already in 24-hour format ELSE CASE WHEN TimeOfDay = 'AM' THEN NumericTime -- Already suitable for 24-hour format ELSE NumericTime + INTERVAL '12' HOUR -- Convert 'PM' time to 24-hour format END END AS MyFinalTime, CAST(Sched_St_Date AS DATE) + CAST(MyFinalTime AS INTERVAL HOUR TO MINUTE) AS Sched_St_Timestamp FROM DB.TBL
我无法访问要检查的TD系统,因此可能存在一些语法错误。您可能需要修改逻辑以适合您的实际数据。让我知道结果如何。