在SQL中,可以使用PIVOT和UNPIVOT來實現行列轉換,具體方法如下:
SELECT *
FROM (
SELECT product_category, total_sales
FROM sales_data
) AS src
PIVOT (
SUM(total_sales)
FOR product_category IN ('A', 'B', 'C', 'D')
) AS pivot_table;
SELECT product_category, total_sales
FROM (
SELECT 'A' AS category_1, 'B' AS category_2, 'C' AS category_3, 'D' AS category_4,
total_sales_1, total_sales_2, total_sales_3, total_sales_4
FROM sales_data
) AS src
UNPIVOT (
total_sales FOR product_category IN (category_1, category_2, category_3, category_4)
) AS unpivot_table;
通過使用PIVOT和UNPIVOT,可以方便地實現行列轉換。