Oracle SQL重新格式化表

时间:2018-02-14 11:05:55

标签: sql oracle12c

我有一张这样的表:

COMPANY    ZONE    SITE    DATE    KWHTOTAL    KWHIT    KWHCLIMA
   1        0       11  01/01/2018  10000      5000      3000
   2        0       23  01/02/2018  7000       4000      1500
...

我需要将表格转换为此

COMPANY    ZONE    SITE    DATE       KWH    TYPE
   1        0       11   01/01/2018  10000   KWHTOTAL
   1        0       11   01/01/2018  5000    KWHIT
   1        0       11   01/01/2018  3000    KWHCLIMA
   2        0       23   01/02/2018  7000    KWHTOTAL
   2        0       23   01/02/2018  4000    KWHIT
   2        0       23   01/02/2018  1500    KWHCLIMA

...

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

一种方法是使用union all。但是,Oracle 12c支持横向连接。所以你可以这样做:

select t.COMPANY, t.ZONE, t.SITE, t.DATE, tt.KWH, tt.TYPE
from t cross apply
     (select 'KWHTOTAL' as type, KWHTOTAL as kwh from dual union all
      select 'KWHIT' as type, KWHIT as kwh from dual union all
      select 'KWHCLIMA' as type, KWHCLIMA as kwh from dual
     ) tt;

答案 1 :(得分:1)

您可以尝试使用UNPIVOT,这应该在Oracle 12c中支持:

SELECT *
FROM your_table
UNPIVOT (KWH FOR kwh_field IN (KWHTOTAL AS 'KWHTOTAL', KWHIT AS 'KWHIT',
    KWHCLIMA AS 'KWHCLIMA'))