Oracle PIVOT 函數是一種將行數據轉換為列數據的方法,它可以讓你在查詢中動態地創建聚合表
以下是一個使用 PIVOT 函數和其他函數組合的示例:
WITH sales_data AS (
SELECT 'A' AS product, 'Q1' AS quarter, 100 AS sales FROM DUAL UNION ALL
SELECT 'A' AS product, 'Q2' AS quarter, 200 AS sales FROM DUAL UNION ALL
SELECT 'B' AS product, 'Q1' AS quarter, 300 AS sales FROM DUAL UNION ALL
SELECT 'B' AS product, 'Q2' AS quarter, 400 AS sales FROM DUAL
)
SELECT *
FROM (
SELECT product, quarter, sales
FROM sales_data
)
PIVOT (
SUM(sales) AS total_sales
FOR quarter IN ('Q1', 'Q2')
);
在這個示例中,我們首先創建了一個名為 sales_data
的臨時表,其中包含產品、季度和銷售額。然后,我們使用 PIVOT 函數對這些數據進行轉換,計算每個產品在每個季度的總銷售額。
除了 PIVOT 函數之外,我們還可以使用其他函數來處理這些數據。例如,我們可以使用 GROUP BY 函數對結果進行分組,或者使用 ORDER BY 函數對結果進行排序。以下是一個使用 GROUP BY 和 ORDER BY 函數的示例:
WITH sales_data AS (
SELECT 'A' AS product, 'Q1' AS quarter, 100 AS sales FROM DUAL UNION ALL
SELECT 'A' AS product, 'Q2' AS quarter, 200 AS sales FROM DUAL UNION ALL
SELECT 'B' AS product, 'Q1' AS quarter, 300 AS sales FROM DUAL UNION ALL
SELECT 'B' AS product, 'Q2' AS quarter, 400 AS sales FROM DUAL
)
SELECT product, SUM('Q1'_total_sales) AS q1_sales, SUM('Q2'_total_sales) AS q2_sales
FROM (
SELECT product, quarter, sales
FROM sales_data
)
PIVOT (
SUM(sales) AS total_sales
FOR quarter IN ('Q1', 'Q2')
)
GROUP BY product
ORDER BY product;
在這個示例中,我們首先使用 PIVOT 函數將銷售數據轉換為每個產品在每個季度的總銷售額。然后,我們使用 GROUP BY 函數對產品進行分組,并使用 ORDER BY 函數對結果進行排序。最后,我們使用 SUM 函數計算每個產品在每個季度的總銷售額。