2017-06-19 42 views
-2

我有以下格式的表:如何透视表的结果吗?

----------------------- 
| Red | Blue | Yellow | 
----------------------- 
| 23 | 34 | 343 | 
----------------------- 

我试图找到利用,我可以在下面的格式选择结果的方式:

------------------ 
| Type | Count | 
------------------ 
| Red | 23 | 
| Blue | 34 | 
| Yellow | 343 | 
------------------ 

我使用的条件,以便有总是在结果一行。

你能告诉我任何方式,我可以实现这一目标吗?

我试过谷歌,找到了枢轴选项,但它需要聚合函数,我不知道它将如何应用于我的问题。

+0

你只是尝试谷歌问题了吗? https://blogs.oracle.com/sql/how-to-convert-rows-to-columns-and-back-again-with-sql-aka-pivot-and-unpivot#pivot –

回答

1

,你可以使用union

select 'Red' type, Red 
from my_table 
union 
select 'Blue' type, Blue 
from my_table 
union 
select 'Yellow' type, Yellow 
from my_table 
2

你需要一个UNPIVOT操作:

with yourTable(Red, Blue, Yellow) as (
    select 23, 34, 343 from dual 
)  
select * 
from yourTable 
unpivot (count for Type in (Red as 'Red', Blue as 'Blue', Yellow as 'Yellow')) 

Here你罚款PIVOT/UNPIVOT一些有用的例子。