Thursday, 23 July 2015

Convert Vertical records to Horizontal -Query

SQL> select * from test_table;
METRIC     CURRENTVAL LASTVALUE  AVERAGEVAL TREND
---------- ---------- ---------- ---------- ----------
Metric1    10%        20%        30%        UP
Metric2    30%        20%        10%        DOWN
Metric3    10%        10%        10%        UNCHANGED
Metric4    10%        20%        10%        Variable
Metric5    30%        60%        90%        UP

SQL> with
  2    lines as (select level line from dual connect by level <= 5),
  3    cols as (select level col from dual connect  by level <= 5)
  4  select max(decode(col, 1,
  5                    decode(line, 1, metric,
  6                                 2, CurrentValue,
  7                                 3, lastvalue,
  8                                 4, AverageValue,
  9                                 5, trend))) col1,
 10         max(decode(col, 2,
 11                    decode(line, 1, metric,
 12                                 2, CurrentValue,
 13                                 3, lastvalue,
 14                                 4, AverageValue,
 15                                 5, trend))) col2,
 16         max(decode(col, 3,
 17                    decode(line, 1, metric,
 18                                 2, CurrentValue,
 19                                 3, lastvalue,
 20                                 4, AverageValue,
 21                                 5, trend))) col3,
 22         max(decode(col, 4,
 23                    decode(line, 1, metric,
 24                                 2, CurrentValue,
 25                                 3, lastvalue,
 26                                 4, AverageValue,
 27                                 5, trend))) col4,
 28         max(decode(col, 5,
 29                    decode(line, 1, metric,
 30                                 2, CurrentValue,
 31                                 3, lastvalue,
 32                                 4, AverageValue,
 33                                 5, trend))) col5      
 34  from lines, cols,
 35       (select rownum rn, test_table.* from test_table)
 36  where rn = col
 37  group by line
 38  order by line
 39  /
COL1       COL2       COL3       COL4       COL5
---------- ---------- ---------- ---------- ----------
Metric1    Metric2    Metric3    Metric4    Metric5
10%        30%        10%        10%        30%
20%        20%        10%        20%        60%
30%        10%        10%        10%        90%
UP         DOWN       UNCHANGED  Variable   UP

No comments:

Post a Comment