将列转换为oracle 11gR1中的行

时间:2014-09-05 11:14:35

标签: sql oracle11g unpivot

我在这个网站上看到很多例子,但我仍然没有任何解决方案。所以我发布了这个问题。
请建议我如何解决这个问题。我正在研究oracle 11gR1版本

year         price     Quantity
1991           10        50
2008           20        96

我希望输出为

1991  10
1991  20
2008  50
2008  96

我尝试使用pivot功能但没有实现并因为SQL命令没有正确终止而获得异常。
以下是我的查询。我不太喜欢sql。

select * from   (select year, price ,quanty from my_table )
       pivot( min(year)  year  in (price, quanty) );

编辑以上问题:

select year, value
from my_table
unpivot
(
  value
  for col in (price, quantity)
) u

对于上面的查询,如果我还有一个名称的产品名称是varchar,iam得到并且我在上面的查询中传递了该列,如下所示。

select year, value
    from my_table
    unpivot
    (
      value
      for col in (price, quantity,productname)
    ) u

错误

ORA-01790:表达式必须与对应表达式具有相同的数据类型

请@BlueFeet就此提出建议。

2 个答案:

答案 0 :(得分:3)

您似乎需要UNPIVOT而非枢轴。 unpivot是将多行转换为多列的过程。

由于您使用的是Oracle 11g,因此可以使用unpivot函数:

select year, value
from my_table
unpivot
(
  value
  for col in (price, quantity)
) u

请参阅SQL Fiddle with Demo

您也可以使用UNION ALL

来撰写此内容
select year, price as value
from my_table
union all
select year, quantity as value
from my_table

请参阅SQL Fiddle with Demo

基于您还希望在最终结果中包含varchar列的事实,您需要将列转换为所有相同的数据类型 - 您可以在子查询中执行此操作:

select year, value
from
(
  select year, 
    to_char(price) as price,
    to_char(quantity) as quantity,
    productname
  from my_table
)
unpivot
(
  value
  for col in (price, quantity, productname)
) u;

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

试试这个:

with t(year, price, Quantity) as(
  select 1991, 10, 50 from dual union all
  select 2008, 20, 96 from dual 
)
select year, new_col1
  from t
unpivot (
  new_col1 for new_col in (price, quantity))

YEAR    NEW_COL1
----------------
1991    10
1991    50
2008    20
2008    96

了解更多here

相关问题