从 varchar 中提取日期

Extract date from varchar

我有一个 table 包含这些信息:

July 16th 2018, 11:16:35.408    July 16th 2018, 11:16:35.408    appointmentCard flip    event       5afa7e01-6045-4ff5-b2d7-1933cd16ebca
July 16th 2018, 11:16:18.649    July 16th 2018, 11:16:18.649    5afa7e01-6045-4ff5-b2d7-1933cd16ebca

我需要的是在两个不同的列中提取日期和时间。 我试过:

select
    to_char(mlk.time, 'yyyy-mm-dd') as Date,
    to_char(mlk.time, 'HH24:MI') as Hours
from main_source_multichannel mlk 
    inner join main_source_orders ord on mlk.trackingid = ord.trackingid

没有成功,Postgresql 给我这个错误:

SQL Error [42883]: ERROR: function to_char(character varying) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.
  Position: 10
  ERROR: function to_char(character varying) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.
  Position: 10
  ERROR: function to_char(character varying) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.
  Position: 10

我做错了什么? 谢谢

我可能会在您的 SELECT 中尝试类似以下内容。

SELECT
to_char((mlk.time)::TIMESTAMP) , 'yyyy-mm-dd')    AS date
,to_char((mlk.time)::TIMESTAMP), 'HH24:MI')       AS hours

如果可以的话,我也会尝试将数据存储为 TIMESTAMP 如果您无法将该列转换为 ::TIMESTAMP,那么您可能需要修复这些记录。

日期的格式使其比需要的稍微复杂一些。我会使用子查询将其解析为时间戳,然后提取日期和时间就变成了一件简单的事情。以下是如何执行此操作的示例:SQL Fiddle

在你的情况下,类似于:

WITH dates AS (
  SELECT to_timestamp(mlk.time, 'MonBDDBBBYYYYBBHH:MI:SS:MS') AS dateTime
  FROM main_source_multichannel mlk 
  INNER JOIN main_source_orders ord on mlk.trackingid = ord.trackingid
)
SELECT dateTime::date AS theDate, dateTime::time AS theTime
FROM dates

正如其他答案所建议的那样,将您的数据存储为适当的时间戳将消除对子查询的需要,您只需要一个简单的 SELECT.