I want to convert a column with mixed formats like "1 day 07:00:00" and "2 days" into hours.
Here's a query that should work in Amazon Redshift:
SELECT
CASE
WHEN POSITION('day', estimated_time_to_pickup) > 0 THEN
24 * CAST(SPLIT_PART(estimated_time_to_pickup, ' ', 1) AS INTEGER) +
EXTRACT(HOUR FROM TO_TIMESTAMP(SUBSTRING(estimated_time_to_pickup, POSITION('day', estimated_time_to_pickup) + 3), 'HH24:MI:SS'))
ELSE
24 * CAST(TRIM(' days' FROM estimated_time_to_pickup)::INTEGER)
END AS estimated_time_in_hours
FROM
"dev"."staging"."stg_zidship__service_levels_servicelevel"
LIMIT 100;
You can use the
CASE WHEN
clause along with regular expressions to extract the relevant information. Here's an example query:Replace
your_column_with_days
with the actual name of the column in your table that stores the time in days, andyour_table
with the actual name of your table.This query checks two patterns using regular expressions. The first pattern is for cases like '2 days', and the second pattern is for cases like '1 day 07:00:00'. The
CASE WHEN
clause then calculates the corresponding hours based on the matched pattern.