基于SQL Oracle中的数据的多行到多列

时间:2018-09-17 11:29:24

标签: sql oracle

sample data and expected output的输出将作为图像

SQL Oracle查询示例

select * from (
  select *  from (
    with fifteen as (select trunc(sysdate) + (level * 15)/(24*60) c_time from dual connect by level <= (24*60) / 15 )
    select to_number(to_char(c_time, 'hh')) HR,to_char(c_time, 'hh24:mi')||' - '||to_char(c_time+ 15 / (24 * 60), 'hh24:mi') TimeSlots 
    from fifteen 
    where extract(hour from cast (c_time as timestamp)) between 2 and 5 
   ) t
)  

1 个答案:

答案 0 :(得分:1)

Oracle Query 1

with fifteen as ( 
  select CAST( TRUNC( sysdate ) AS TIMESTAMP ) + level * INTERVAL '15' MINUTE c_time,
         MOD( LEVEL,4 ) AS quarter
  from dual 
  connect by level <= (24*60) / 15 
) 
SELECT "2", "3", "4", "5"
FROM   (
  select EXTRACT( HOUR FROM c_time ) HR,
         quarter,
         to_char(c_time, 'hh24:mi')||' - '||to_char(c_time + INTERVAL '15' MINUTE, 'hh24:mi') TimeSlots  
  from   fifteen
) t
PIVOT( MAX( timeslots ) FOR HR IN ( 2, 3, 4, 5 ) )
ORDER BY quarter

Oracle Query 2

SELECT TO_CHAR(two,  'HH24:MI') || ' - ' || TO_CHAR(two  +INTERVAL '15' MINUTE,'HH24:MI') AS "2",
       TO_CHAR(three,'HH24:MI') || ' - ' || TO_CHAR(three+INTERVAL '15' MINUTE,'HH24:MI') AS "3",
       TO_CHAR(four ,'HH24:MI') || ' - ' || TO_CHAR(four +INTERVAL '15' MINUTE,'HH24:MI') AS "4",
       TO_CHAR(five ,'HH24:MI') || ' - ' || TO_CHAR(five +INTERVAL '15' MINUTE,'HH24:MI') AS "5"
FROM   (
  SELECT DATE '1970-01-01' + INTERVAL '2' HOUR + INTERVAL '15' MINUTE * (LEVEL - 1) AS two,
         DATE '1970-01-01' + INTERVAL '3' HOUR + INTERVAL '15' MINUTE * (LEVEL - 1) AS three,
         DATE '1970-01-01' + INTERVAL '4' HOUR + INTERVAL '15' MINUTE * (LEVEL - 1) AS four,
         DATE '1970-01-01' + INTERVAL '5' HOUR + INTERVAL '15' MINUTE * (LEVEL - 1) AS five
  FROM   DUAL
  CONNECT BY LEVEL <= 4
)

输出

2             3             4             5
------------- ------------- ------------- -------------
02:00 - 02:15 03:00 - 03:15 04:00 - 04:15 05:00 - 05:15
02:15 - 02:30 03:15 - 03:30 04:15 - 04:30 05:15 - 05:30
02:30 - 02:45 03:30 - 03:45 04:30 - 04:45 05:30 - 05:45
02:45 - 03:00 03:45 - 04:00 04:45 - 05:00 05:45 - 06:00