我有几个返回SYS_REFCURSOR
的程序。一个叫cust_cursor
,另一个叫prod_cursor
。后者存储产品的ID和数量。到目前为止,我能够打印每个单独的数量,如下面的匿名块所示。
DECLARE
cust_cursor SYS_REFCURSOR;
cust_id ex1.address_detail.id_customer%TYPE;
addr_id ex1.address_detail.id_address%TYPE;
prod_cursor SYS_REFCURSOR;
prod_id ex1.SALES_ORDER_DETAIL.ID_PROD%TYPE;
prod_qty ex1.SALES_ORDER_DETAIL.ORDER_QTY%TYPE;
BEGIN
ex1.INFO_SALES.TOP_CUSTOMERS (cust_cursor);
LOOP
FETCH cust_cursor INTO cust_id, addr_id;
EXIT WHEN cust_cursor%NOTFOUND;
ex1.info_sales.top_products (addr_id, prod_cursor);
DBMS_OUTPUT.put_line (
'Customer' || CHR (9) || '|' || CHR (9) || 'Address');
DBMS_OUTPUT.put_line (
cust_id || CHR (9) || CHR (9) || '|' || CHR (9) || addr_id);
DBMS_OUTPUT.put_line (
'Product' || CHR (9) || '|' || CHR (9) || 'Quantity');
LOOP
FETCH prod_cursor INTO prod_id, prod_qty;
EXIT WHEN prod_cursor%NOTFOUND;
DBMS_OUTPUT.put_line (
prod_id || CHR (9) || CHR (9) || '|' || CHR (9) || prod_qty);
END LOOP;
CLOSE prod_cursor;
DBMS_OUTPUT.put_line (
'------------------------------------------------------------');
END LOOP;
CLOSE cust_cursor;
END;
如何在prod_cursor
中计算每位客户的这些数量的平均值?
我提供了一个示例查询来获取prod_cursor
。
SELECT products.ID_PROD, products.ORDER_QTY
FROM (SELECT sale.id_sales_order,
sale.customer_id,
sale.bill_address_id,
detail.id_prod,
detail.unit_price,
detail.order_qty,
detail.unit_price * detail.order_qty AS "Total Sales",
ROW_NUMBER ()
OVER (ORDER BY detail.unit_price * detail.order_qty DESC)
AS product_rank
FROM ex1.sales sale
INNER JOIN ex1gon.sales_order_detail detail
ON sale.ID_SALES_ORDER = detail.ID_SALES_ORDER
WHERE sale.BILL_ADDRESS_ID = 100) products
WHERE products.PRODUCT_RANK < 5;
答案 0 :(得分:2)
回答你关于平均单行结果的评论,光标中所有行的值都是相同的,这取决于你如何在fetch中使用它。
您可以使用analityc功能
SELECT products.ID_PROD, products.ORDER_QTY,
avg(products.ORDER_QTY) over (partition by products.customer_id) AvgQnty
FROM (SELECT sale.id_sales_order,
sale.customer_id,
sale.bill_address_id,
detail.id_prod,
detail.unit_price,
detail.order_qty,
detail.unit_price * detail.order_qty AS "Total Sales",
ROW_NUMBER ()
OVER (ORDER BY detail.unit_price * detail.order_qty DESC)
AS product_rank
FROM ex1.sales sale
INNER JOIN ex1gon.sales_order_detail detail
ON sale.ID_SALES_ORDER = detail.ID_SALES_ORDER
WHERE sale.BILL_ADDRESS_ID = 100) products
WHERE products.PRODUCT_RANK < 5;