提取小时和分钟不起作用

时间:2014-10-20 14:15:08

标签: sql oracle

我正在尝试从格式

的日期中提取小时和分钟
2012/12/01 02:03:44

我的代码看起来很像

SELECT to_char(t.start_date, 'DD-MON-YY HH24:MI:SS')                              AS Start_DATE, 
       to_char(t.resolved_date, 'DD-MON-YY HH24:MI:SS')                           AS Closed_DATE, 
       extract(MINUTE FROM TO_TIMESTAMP(t.start_date, 'YYYY/MON/DD HH24:MI:SS'))  AS Start_DATE_min,
       extract(MINUTE FROM TO_TIMESTAMP(t.closed_date, 'YYYY/MON/DD HH24:MI:SS')) AS Closed_DATE_min,
       extract(HOUR FROM TO_TIMESTAMP(t.start_date, 'DD-MON-YYYY HH24:MI:SS'))    AS Start_DATE_h, 
       extract(HOUR FROM TO_TIMESTAMP(t.closed_date, 'DD-MON-YYYY HH24:MI:SS'))   AS Closed_DATE_h 
FROM   t 

但是在提取字段中我只得到0。

知道我做错了吗?

2 个答案:

答案 0 :(得分:2)

SELECT to_char(t.start_date, 'DD-MON-YY HH24:MI:SS')                              AS Start_DATE, 
       to_char(t.resolved_date, 'DD-MON-YY HH24:MI:SS')                           as closed_date, 
       extract(minute from cast(t.start_date as timestamp))  as start_date_min,
       extract(MINUTE FROM cast(t.closed_date as timestamp)) AS Closed_DATE_min,
       extract(HOUR FROM cast(t.start_date as timestamp))    AS Start_DATE_h, 
       extract(HOUR FROM cast(t.closed_date as timestamp))   AS Closed_DATE_h 
FROM   t 



SELECT to_char(t.start_date, 'DD-MON-YY HH24:MI:SS')                              AS Start_DATE, 
       to_char(t.resolved_date, 'DD-MON-YY HH24:MI:SS')                           as closed_date, 
       to_char(t.start_date, 'MI')  as start_date_min,
       to_char(t.closed_date, 'MI') as closed_date_min,
       to_char(t.start_date, 'HH24')    as start_date_h, 
       to_char(t.closed_date, 'HH24')   AS Closed_DATE_h 
FROM   t

您的代码存在问题:
TO_TIMESTAMP(t.start_date,'DD-MON-YYYY HH24:MI:SS') - 第一个参数是char,因此Oracle使用会话NLS设置将datetime列“start_date”转换为char。它可能与您的面具'DD-MON-YYYY HH24:MI:SS'

不同

答案 1 :(得分:0)

尝试:

SELECT to_char(t.start_date,    'DD-MON-YY HH24:MI:SS')                AS Start_DATE, 
       to_char(t.resolved_date, 'DD-MON-YY HH24:MI:SS')                AS Closed_DATE, 
       extract(MINUTE FROM t.start_date  ) AS Start_DATE_min,
       extract(MINUTE FROM t.closed_date ) AS Closed_DATE_min,
       extract(HOUR   FROM t.start_date  ) AS Start_DATE_h, 
       extract(HOUR   FROM t.closed_date ) AS Closed_DATE_h 
FROM   t 

我假设您使用日期时间格式存储日期,而不需要将它们转换为时间戳。

更新:如果您有DATE类型,则从没有此信息的类型中提取分钟和小时信息毫无意义。 它解释了您正在读零的原因将数据类型更改为DATETIME。这就像从INTEGER中提取小数。或者只是将零和保存CPU:

SELECT to_char(t.start_date,    'DD-MON-YY HH24:MI:SS')                AS Start_DATE, 
       to_char(t.resolved_date, 'DD-MON-YY HH24:MI:SS')                AS Closed_DATE, 
       0 AS Start_DATE_min,
       0 AS Closed_DATE_min,
       0 AS Start_DATE_h, 
       0 AS Closed_DATE_h 
FROM   t

P.S。在问题中它说:“我试图从格式的日期提取时间和分钟 2012/12/01 02:03:44“。如何在不丢失时间信息的情况下将其存储在日期?