Pivot函數在Oracle數據庫中用于將行數據轉換為列數據,從而使數據更易于分析和查看
示例:
SELECT *
FROM sales_data
PIVOT (
SUM(sales) AS total_sales,
AVG(profit) AS avg_profit
FOR product_id IN (1001 AS 'Product A', 1002 AS 'Product B')
);
示例:
DECLARE
v_cols CLOB;
BEGIN
SELECT LISTAGG('''' || product_name || ''' AS "' || product_name || '"', ', ') WITHIN GROUP (ORDER BY product_name)
INTO v_cols
FROM (SELECT DISTINCT product_name FROM sales_data);
EXECUTE IMMEDIATE '
SELECT *
FROM sales_data
PIVOT (
SUM(sales) AS total_sales,
AVG(profit) AS avg_profit
FOR product_name IN (' || v_cols || ')
)';
END;
/
示例:
SELECT *
FROM sales_data
PIVOT JSON (
SUM(sales) AS total_sales,
AVG(profit) AS avg_profit
FOR product_id IN (1001 AS 'Product A', 1002 AS 'Product B')
);
請注意,上述示例中的SQL語法可能因您使用的Oracle數據庫版本而有所不同。在使用這些新特性之前,請確保您的數據庫版本支持它們。