自动填充“time_hour”表

时间:2017-10-15 09:50:53

标签: sql oracle

我要求在“time_hours”表中一天24小时存储。这是我桌子的结构:

Create table time_hours
    (HOURS number,
    HOUR_RANGE VARCHAR (20),
    HOUR_MIN VARCHAR (20),
    HOUR_MAX VARCHAR(20));

这是我到目前为止的脚本:

Insert into time_hours(HOURS,
   HOUR_RANGE,
   HOUR_MIN,
   HOUR_MAX)
Select 
to_number(to_char(t,'HH24'),'00'),
to_char(t,'HH24:MI:SS'),
to_char(t,'HH24:MI:SS'),
to_char(t,'HH24:MI:SS')
FROM
    (
    Select trunc(sysdate) + (level-1)/24 as t
    FROM dual
    Connect by level <=24
    );

结果是:

Hours | HOUR_RANGE | HOUR_MIN | HOUR_MAX
0       00:00:00    00:00:00   00:00:00  
1       01:00:00     01:00:00   01:00:00     
..    
23      23:00:00     23:00:00   23:00:00  

但是我需要这个输出:

Hours | HOUR_RANGE | HOUR_MIN | HOUR_MAX
0       00h-00h59    00:00:00   00:59:59
1       01h00-01h59  01:00:00   01:59:59
2       02h00-02h59  02:00:00   02:59:59
..      ..           ..         .. 
23      23h00-23h59  23:00:00   23.59.59

我的问题: 如何格式化“HOUR_RANGE”和“HOUR_MAX”列以获得预期的输出?

提前感谢大家的帮助

3 个答案:

答案 0 :(得分:2)

您可以使用:

Select 
  to_number(to_char(t,'HH24'),'00') AS Hours,
  to_char(t,'HH24"h"MI"-"HH24"h59"') AS HOUR_RANGE,
  to_char(t,'HH24:MI:SS') AS HOUR_MIN,
  to_char(t+1/24-1/(24*3600),'HH24:MI:SS') AS HOUR_MAX
FROM (Select trunc(sysdate) + (level-1)/24 as t
    FROM dual
    Connect by level <=24 );

<强> Rextester Demo

答案 1 :(得分:0)

我认为您可以使用以下代码。

您可以使用管道连接字符。

您可以使用一些算术运算来获得给定小时的最大分钟数和秒数; 1/24 * 60 = 1/1440将日期值添加一分钟。 1/24 * 60 * 60 = 1/86400,为日期值添加秒。

INSERT INTO time_hours (HOURS, HOUR_RANGE, HOUR_MIN, HOUR_MAX)
  SELECT
    to_number(to_char(t, 'HH24'), '00'),
    to_char(t, 'HH24') || 'h' || to_char(t, 'MI') || '-' || to_char(t, 'HH24') || 'h59',
    to_char(t, 'HH24:MI:SS'),
    to_char(t + 1/86400*59 + 1/1440*59, 'HH24:MI:SS')
  FROM (SELECT trunc(SYSDATE) + (LEVEL - 1) / 24 AS t
        FROM dual
        CONNECT BY LEVEL <= 24);

Query Result

答案 2 :(得分:0)

毕竟,它只是包含小时加上其他一些字符的字符串。根本不需要日期转换。

insert into time_hours(hours, hour_range, hour_min, hour_max)
select 
  level-1 as hours,
  to_char(level-1, '00') || 'h00-' || to_char(level-1, '00') || 'h59' as hour_range,
  to_char(level-1, '00') || ':00:00'as hour_min,
  to_char(level-1, '00') || ':59:59'as hour_max
from dual connect by level <= 24;