问题描述
我在 Oracle PL SQL Developer 中使用数据透视如下:
这工作正常,但我不想每次添加新列或更改一个列(即 Group4、5、6 等)时都必须进行编辑,因此我尝试了如下子查询:
这会导致以下错误:ORA-00936:缺少表达式.
经过一番研究,似乎可以用 XML 生成结果,因此我尝试了以下操作:
这实际上会生成所需的数据,但采用 XML 格式.所以我的问题是,如何在 PL SQL Developer 中将 XML 结果转换为标准表格式?或者,如果我想将生成的 XML 文件带入像 Crystal Reports 这样的工具中,我需要有这些结果的模式文件.这是否可以轻松地在 SQL 中自动生成?
您是否会考虑使用 PIPELINED 函数来实现您的目标?
我写了一个这样的函数的例子.该示例基于 Tom Kyte 文章中的表格、示例数据和 PIVOT
查询,您可以在他的网站上找到这些文章:
Tom Kyte 关于 PIVOT/UNPIVOT 的文章
Tom Kyte 关于 PIPELINED 函数的文章
该示例的工作原理如下.
我们创建两种类型:
- t_pivot_test_obj - 包含我们想要从 XML 中检索的列的类型
- t_pivot_test_obj_tab - 上述对象的嵌套表类型.
然后我们创建一个 PIPELINED 函数,其中包含带有 PIVOT
的查询,它生成 XML(因此您不必对要转换的值进行硬编码).此函数从生成的 XML 中提取数据,并在生成行时将 (PIPE) 行传递给调用查询(即时 - 它们不是一次性生成的,这对性能很重要).
最后,您编写一个查询,该查询从该函数中选择记录(最后是此类查询的示例).
输出:
I'm using pivot in Oracle PL SQL Developer as follows:
This works fine, but I don't want to have to edit every time a new column is added or one is changed (i.e. Group4, 5, 6 etc), so I tried a sub-query as follows:
This results in the following error: ORA-00936: missing expression.
After some research, it appears that I can generate the results with XML, so I tried the following:
This actually generates the desired data, but in XML format. So my question is, how can I convert the XML results into standard table format within PL SQL Developer? Or, if I want to bring the generated XML file into a tool like Crystal Reports, I need to have a schema file for these results. Is that something that can easily be auto generated within the SQL?
Would you consider using PIPELINED function to achieve your goal?
I have written a an example of such a function. The example is based on the table, sample data and PIVOT
query from Tom Kyte's articles which you can find on his site:
Tom Kyte's article about PIVOT/UNPIVOT
Tom Kyte's article about PIPELINED functions
The example works as follows.
We create two types:
- t_pivot_test_obj - type which holds columns we want to retrieve from XML
- t_pivot_test_obj_tab - nested table type of above objects.
Then we create a PIPELINED function which contains the query with PIVOT
, which generates XML (so you do not have to hard-code the values you want to pivot over). This function extracts data from generated XML and passes (PIPEs) rows to the calling query as they are generated (on the fly - they are not generated all at once which is important for performance).
Finally, you write a query which selects records from that function (at the end is an example of such a query).
Output:
这篇关于带有子查询的 Oracle 数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!