使用 SQL 创建列出两个时间戳之间的小时数的列

问题描述 投票:0回答:1

在 Oracle 中使用 SQL——我需要创建一个新列,列出两个时间戳之间的小时数。下面是一个示例,其中需要创建“hour_list”:

表1:

    start                     finish                      hour_list
1/7/2024 4:57:00 AM    1/7/2024 1:29:00 PM        4,5,6,7,8,9,10,11,12,13
1/7/2024 1:29:00 PM    1/7/2024 3:10:00 PM                13,14,15
1/8/2024 4:40:00 AM    1/8/2024 11:10:00 AM          4,5,6,7,8,9,10,11
sql oracle toad
1个回答
0
投票

这是一种选择:

SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi';

Session altered.

样本数据:

SQL> with test (start_time, end_time) as
  2    (select to_date('01.07.2024 04:57', 'dd.mm.yyyy hh24:Mi'),
  3            to_date('01.07.2024 13:29', 'dd.mm.yyyy hh24:mi') from dual union all
  4     select to_date('01.07.2024 13:29', 'dd.mm.yyyy hh24:Mi'),
  5            to_date('01.07.2024 15:10', 'dd.mm.yyyy hh24:mi') from dual
  6    )

查询聚合示例表中每行的 START 和 END 时间之间的小时数:

  7  select start_time, end_time,
  8  listagg(to_char(start_time + (column_value - 1)  / 24 , 'hh24'), ', ')
  9      within group (order by column_value) as hour_list
 10  from test cross join
 11    table(cast(multiset(select level from dual
 12                        connect by level <= ceil((end_time - start_time) * 24) + 1
 13                       ) as sys.odcinumberlist))
 14  group by start_time, end_time;

START_TIME       END_TIME         HOUR_LIST
---------------- ---------------- ----------------------------------------
01.07.2024 04:57 01.07.2024 13:29 04, 05, 06, 07, 08, 09, 10, 11, 12, 13
01.07.2024 13:29 01.07.2024 15:10 13, 14, 15

SQL>
© www.soinside.com 2019 - 2024. All rights reserved.