溫馨提示×

sql行列轉(zhuǎn)換的方法是什么

sql
小億
82
2024-04-08 10:05:39
欄目: 云計算

在SQL中,可以使用PIVOT和UNPIVOT來實現(xiàn)行列轉(zhuǎn)換,具體方法如下:

  1. PIVOT:將行數(shù)據(jù)轉(zhuǎn)換為列數(shù)據(jù)。使用PIVOT時,需要指定要轉(zhuǎn)換的行數(shù)據(jù)列和要轉(zhuǎn)換后的列數(shù)據(jù)列。例如,將銷售數(shù)據(jù)按照不同的產(chǎn)品分類轉(zhuǎn)換為列數(shù)據(jù):
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;
  1. UNPIVOT:將列數(shù)據(jù)轉(zhuǎn)換為行數(shù)據(jù)。使用UNPIVOT時,需要指定要轉(zhuǎn)換的列數(shù)據(jù)列和要轉(zhuǎn)換后的行數(shù)據(jù)列。例如,將不同產(chǎn)品分類的銷售數(shù)據(jù)轉(zhuǎn)換為行數(shù)據(jù):
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,可以方便地實現(xiàn)行列轉(zhuǎn)換。

0