我正在研究Oracle。我有这个大的属性索引器表(THE_TABLE
),其列是
[ObjectID | CategoryID | Property1 | Property2 | ... | PropertyN]
其中N
已知设计。所有Property%
列都是相同大小的VARCHAR2,ObjectID是Numeric。现在,我想创建一个包含以下查询结果的物化视图:
select distinct CategoryID, (select 'Property1' from dual) as PropertyName, Property1 as PropertyValue from THE_TABLE
select distinct CategoryID, (select 'Property2' from dual) as PropertyName, Property2 as PropertyValue from THE_TABLE
...
select distinct CategoryID, (select 'PropertyN' from dual) as PropertyName, PropertyN as PropertyValue from THE_TABLE
换句话说,视图(THE_VIEW
)应包含三列:
[CategoryID | PropertyName | PropertyValue]
并且能够返回链接到特定CategoryID的唯一值。有没有办法创建这样的视图?
请注意,我无法修改THE_TABLE
。
此致 安德烈
答案 0 :(得分:3)
如果我正确理解你的问题,我就不会这样做,但我相信你想要像
这样的东西create materialied view THE_VIEW as
select categoryID, 'property1' propertyName, property1 propertyValue from THE_TABLE union all
select categoryID, 'property2' propertyName, property2 propertyValue from THE_TABLE union all
...
select categoryID, 'propertyN' propertyName, propertyN propertyValue from THE_TABLE
;
答案 1 :(得分:2)
如果您使用的是Oracle 11g,则可以尝试新的pivot / unpivot功能。
这个article对此非常了解,但一般来说,在这种情况下你需要一个UNPIVOT。例如(我目前不在11g实例上,所以这是一个通用示例):
SQL> SELECT *
2 FROM pivoted_data;
JOB D10_SAL D20_SAL D30_SAL D40_SAL
---------- ---------- ---------- ---------- ----------
CLERK 1430 2090 1045
SALESMAN 6160
PRESIDENT 5500
MANAGER 2695 3272.5 3135
ANALYST 6600
5 rows selected.
SQL> SELECT *
2 FROM pivoted_data
3 UNPIVOT (
4 deptsal --<-- unpivot_clause
5 FOR saldesc --<-- unpivot_for_clause
6 IN (d10_sal, d20_sal, d30_sal, d40_sal) --<-- unpivot_in_clause
7 );
JOB SALDESC DEPTSAL
---------- ---------- ----------
CLERK D10_SAL 1430
CLERK D20_SAL 2090
CLERK D30_SAL 1045
SALESMAN D30_SAL 6160
PRESIDENT D10_SAL 5500
MANAGER D10_SAL 2695
MANAGER D20_SAL 3272.5
MANAGER D30_SAL 3135
ANALYST D20_SAL 6600
9 rows selected.
11g上的其他选择。