使用SQL使用每小时列旋转表的最佳方法是什么

时间:2014-08-14 07:20:39

标签: sql database oracle

我有一个带有24小时列的oracle表来记录每小时数据。

"REFERENCE_DAY" DATE,
"VAL_00" NUMBER, 
"VAL_01" NUMBER, 
"VAL_02" NUMBER, 
"VAL_03" NUMBER, 
"VAL_04" NUMBER, 
"VAL_05" NUMBER, 
"VAL_06" NUMBER, 
"VAL_07" NUMBER, 
"VAL_08" NUMBER, 
"VAL_09" NUMBER, 
"VAL_10" NUMBER, 
"VAL_11" NUMBER, 
"VAL_12" NUMBER, 
"VAL_13" NUMBER, 
"VAL_14" NUMBER, 
"VAL_15" NUMBER, 
"VAL_16" NUMBER, 
"VAL_17" NUMBER, 
"VAL_18" NUMBER, 
"VAL_19" NUMBER, 
"VAL_20" NUMBER, 
"VAL_21" NUMBER, 
"VAL_22" NUMBER, 
"VAL_23" NUMBER, 

透视表的最佳方法是什么,这样我可以在一列中添加时间戳,将值作为另一列。我想要选择每一列24次,然后做一个联合,但看起来效率低下。

select REFERENCE_DAY,  VALUE_00 from table
UNION ALL 
select REFERENCE_DAY + 1/24,  VALUE_01 from table
UNION ALL 
select REFERENCE_DAY + 2/24,  VALUE_02 from table
UNION ALL 
......

示例:

输入:

REFERENCE_DAY | VAL_00 | VAL_01 | VAL_02 | VAL_03 | 
7/1/2014      |  1     |    2   |   3    |      4 | 

输出:

REFERENCE_DAY     | value
7/1/2014 00:00:00 | 1
7/1/2014 01:00:00 | 2
7/1/2014 02:00:00 | 3
7/1/2014 03:00:00 | 4

1 个答案:

答案 0 :(得分:0)

如果您使用的是Oracle 11g,则可以使用unpivot功能:

with tab (REFERENCE_DAY , VAL_00 , VAL_01 , VAL_02 , VAL_03) as 
  (select to_date('07/01/2014', 'mm/dd/yyyy'),  1     ,    2   ,   3    ,      4 from dual)
select (REFERENCE_DAY + vals / 24) REFERENCE_DAY, val
  from tab
unpivot (val for vals in (VAL_00 as 0, VAL_01 as 1, VAL_02 as 2, VAL_03 as 3));

输出:

REFERENCE_DAY           VAL
01-JUL-14 12.00.00 AM   1
01-JUL-14 01.00.00 AM   2
01-JUL-14 02.00.00 AM   3
01-JUL-14 03.00.00 AM   4

您必须根据您的要求修改此查询,如下所示

select (REFERENCE_DAY + vals / 24) REFERENCE_DAY, val
      from <your_table>
    unpivot (val for vals in (VAL_00 as 0, VAL_01 as 1, VAL_02 as 2, VAL_03 as 3 ..... VAL_23 as 23));