2

我有一个更大的 SQL,它产生与这个简化示例类似的输出:

SELECT
  5 AS L0,
  2 AS L1,
  3 AS L2,
  4 AS L3
FROM DUAL

当前输出是这一行:

| L0 | L1 | L2 | L3 |
|  5 |  2 |  3 |  4 |


所需的输出是这些列:

| kind | value |
|   0  |   5   |
|   1  |   2   |
|   2  |   3   |
|   3  |   4   |

我知道我可以通过联合选择 4 次来获得这个。我正在寻求建议,如果 union 是我能在这里做的最好的,并且这个输出是否可以通过其他方式实现。

我还发现了许多将列反转为行的示例,但在这里我正在寻找从行到列的反转。

4

2 回答 2

11

请尝试 UnPIVOT:

SELECT substr(kind,2,1) AS kind,"value" FROM 
(    
    SELECT
        5 AS l0,
        2 AS l1,
        3 AS l2,
        4 AS l3
    FROM dual
)temp unpivot include NULLS ("value" FOR kind IN (l0, l1 , l2, l3));

反过来:

 SELECT *   
 FROM 
 (
      SELECT Kind,
             max(Value) Value
      FROM table 
      GROUP BY Kind
 ) PIVOT ( max(Value) FOR Kind IN (L0, L1, L2, L3) );

假设您实际上有一个要查询的表。

于 2011-03-14T16:50:54.767 回答
1

select i - 1 kind,
case when i = 1 then L0 when i = 2 then L1 when i = 3 then L2 when i = 4 then L3 end as value from your_table, (select level as i from dual connect by level <= 4)
这对您的表和“内联视图”进行了 Carteasan 产品。内联视图将输出四行,从 1 到 4。

于 2011-03-15T19:32:36.700 回答