我有一个更大的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次联合选择得到这个。 如果工会是我能在这里做的最好的,如果这个输出可以通过其他方式实现,我正在寻求建议。
我还发现了许多将列反转为行的示例,但我在这里寻找从行到列的反转。
答案 0 :(得分:10)
请尝试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) );
假设您确实有一个要查询的表。
答案 1 :(得分: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.