您会考虑使用PIPELINED功能来实现您的目标吗?
我已经写了一个这样的函数的例子。这个例子是基于表,样本数据和汤姆凯特的文章PIVOT
查询,你可以找到他的网站:
Tom Kyte's article about PIVOT/UNPIVOT
Tom Kyte's article about PIPELINED functions
的例子如下工作。
我们创建两种类型:
- t_pivot_test_obj - 型持有我们想从XML检索
- t_pivot_test_obj_tab列 - 上述目的的嵌套表类型。
然后,我们创建一个PIPELINED函数,其中包含查询PIVOT
,该函数生成XML(因此您不必硬编码想要旋转的值)。该函数从生成的XML中提取数据并将它们传递(PIPE)到生成的调用查询中(即时生成 - 它们不会一次生成,这对性能很重要)。
最后,您编写了一个查询,该查询从该函数中选择记录(最后是此类查询的一个示例)。
CREATE TABLE pivot_test (
id NUMBER,
customer_id NUMBER,
product_code VARCHAR2(5),
quantity NUMBER
);
INSERT INTO pivot_test VALUES (1, 1, 'A', 10);
INSERT INTO pivot_test VALUES (2, 1, 'B', 20);
INSERT INTO pivot_test VALUES (3, 1, 'C', 30);
INSERT INTO pivot_test VALUES (4, 2, 'A', 40);
INSERT INTO pivot_test VALUES (5, 2, 'C', 50);
INSERT INTO pivot_test VALUES (6, 3, 'A', 60);
INSERT INTO pivot_test VALUES (7, 3, 'B', 70);
INSERT INTO pivot_test VALUES (8, 3, 'C', 80);
INSERT INTO pivot_test VALUES (9, 3, 'D', 90);
INSERT INTO pivot_test VALUES (10, 4, 'A', 100);
COMMIT;
CREATE TYPE t_pivot_test_obj AS OBJECT (
customer_id NUMBER,
product_code VARCHAR2(5),
sum_quantity NUMBER
);
/
CREATE TYPE t_pivot_test_obj_tab IS TABLE OF t_pivot_test_obj;
/
CREATE OR REPLACE FUNCTION extract_from_xml RETURN t_pivot_test_obj_tab PIPELINED
AS
v_xml XMLTYPE;
v_item_xml XMLTYPE;
v_index NUMBER;
v_sum_quantity NUMBER;
CURSOR c_customer_items IS
SELECT customer_id, product_code_xml
FROM (SELECT customer_id, product_code, quantity
FROM pivot_test)
PIVOT XML (SUM(quantity) AS sum_quantity FOR (product_code) IN (SELECT DISTINCT product_code
FROM pivot_test));
BEGIN
-- loop through all records returned by query with PIVOT
FOR v_rec IN c_customer_items
LOOP
v_xml := v_rec.product_code_xml;
v_index := 1;
-- loop through all ITEM elements for each customer
LOOP
v_item_xml := v_xml.EXTRACT('/PivotSet/item[' || v_index || ']');
EXIT WHEN v_item_xml IS NULL;
v_index := v_index + 1;
IF v_item_xml.EXTRACT('/item/column[@name="SUM_QUANTITY"]/text()') IS NOT NULL THEN
v_sum_quantity := v_item_xml.EXTRACT('/item/column[@name="SUM_QUANTITY"]/text()').getNumberVal();
ELSE
v_sum_quantity := 0;
END IF;
-- finally, for each customer and item - PIPE the row to the calling query
PIPE ROW(t_pivot_test_obj(v_rec.customer_id,
v_item_xml.EXTRACT('/item/column[@name="PRODUCT_CODE"]/text()').getStringVal(),
v_sum_quantity));
END LOOP;
END LOOP;
END;
/
SELECT customer_id, product_code, sum_quantity
FROM TABLE(extract_from_xml())
;
输出:
CUSTOMER_ID PRODUCT_CODE SUM_QUANTITY
---------------------- ------------ ----------------------
1 A 10
1 B 20
1 C 30
1 D 0
2 A 40
2 B 0
2 C 50
2 D 0
3 A 60
3 B 70
3 C 80
3 D 90
4 A 100
4 B 0
4 C 0
4 D 0
16 rows selected