假設你有一個表,如下所示:是否有替代MULTISET運算符來避免子查詢?
CREATE TABLE EMPLOYEE_SALES
(
EMPLOYEE_ID NUMBER,
PRODUCT_ID NUMBER,
SALE_AMOUNT NUMBER
);
並假定它是填充如下:
+-------------+------------+-------------+ | EMPLOYEE_ID | PRODUCT_ID | SALE_AMOUNT | +-------------+------------+-------------+ | 1 | 100 | 1.05 | | 1 | 200 | 45.67 | | 2 | 100 | 3.25 | | 2 | 200 | 34.29 | +-------------+------------+-------------+
現在,假設我創建一個名爲SALE_TYPE
自定義類型代表一個(PRODUCT_ID, SALE_AMOUNT)
元組:
CREATE TYPE SALE_TYPE IS OBJECT
(
PRODUCT_ID NUMBER,
SALE_AMOUNT NUMBER
);
並假設我還創建了一個名爲SALES_TYPE
的自定義類型,其中repr esents一個TABLE
SALE_TYPE
的:
CREATE TYPE SALES_TYPE IS TABLE OF SALE_TYPE;
我想EMPLOYEE_ID
查詢EMPLOYEE_SALES
表組。對於每個EMPLOYEE_ID
,我希望創建一個SALES_TYPE
包含該員工的銷售。根據該文件,我會做這樣的事情:
SELECT
EMPLOYEE_ID,
CAST
(
MULTISET
(
SELECT
PRODUCT_ID,
SALE_AMOUNT
FROM
EMPLOYEE_SALES inner_employee_sales
WHERE
inner_employee_sales.employee_id = employee_sales.employee_id
) AS SALES_TYPE
) AS SALES
FROM
EMPLOYEE_SALES
GROUP BY
EMPLOYEE_ID
我希望這個查詢產生這樣的事:
+-------------+------------------------------+ | EMPLOYEE_ID | SALES | +-------------+------------------------------+ | 1 | +------------+-------------+ | | | | PRODUCT_ID | SALE_AMOUNT | | | | +------------+-------------+ | | | | 100 | 1.05 | | | | | 200 | 45.67 | | | | +------------+-------------+ | +-------------+------------------------------+ | 2 | +------------+-------------+ | | | | PRODUCT_ID | SALE_AMOUNT | | | | +------------+-------------+ | | | | 100 | 3.25 | | | | | 200 | 34.29 | | | | +------------+-------------+ | +-------------+------------------------------+
有沒有一種方法來達到同樣的效果,而不會發出子查詢(real我正在處理的查詢比這個人爲的例子複雜得多)?例如,有沒有這樣的事情:
SELECT
EMPLOYEE_ID,
CAST
(
COLLECT_ALL_RECORDS_WITHIN_THE_CURRENT_GROUP(
PRODUCT_ID,
SALE_AMOUNT
)
AS SALES_TYPE
) AS SALES
FROM
EMPLOYEE_SALES
GROUP BY
EMPLOYEE_ID
+1:哇,太簡單了! – 2011-03-09 13:20:01