溫馨提示×

oracle多行轉(zhuǎn)列怎么實現(xiàn)

小億
81
2024-09-13 13:38:24
欄目: 云計算

在Oracle中,可以使用PIVOT操作將多行數(shù)據(jù)轉(zhuǎn)換為單列的多個值

假設(shè)有一個名為sales_data的表,其結(jié)構(gòu)如下:

CREATE TABLE sales_data (
  product_id NUMBER,
  month VARCHAR2(10),
  sales_amount NUMBER
);

插入一些示例數(shù)據(jù):

INSERT INTO sales_data VALUES (1, 'January', 100);
INSERT INTO sales_data VALUES (1, 'February', 200);
INSERT INTO sales_data VALUES (2, 'January', 150);
INSERT INTO sales_data VALUES (2, 'February', 250);

要將這些數(shù)據(jù)轉(zhuǎn)換為每個產(chǎn)品ID對應(yīng)一行,每個月對應(yīng)一列的格式,可以使用以下查詢:

SELECT * FROM (
  SELECT product_id, month, sales_amount
  FROM sales_data
)
PIVOT (
  SUM(sales_amount)
  FOR month IN ('January' AS january, 'February' AS february)
);

查詢結(jié)果如下:

PRODUCT_ID JANUARY FEBRUARY
---------- -------- --------
         1       100      200
         2       150      250

在這個例子中,我們首先從sales_data表中選擇product_idmonthsales_amount列。然后,我們使用PIVOT操作將month列的值轉(zhuǎn)換為列名,并對sales_amount列求和。最后,我們使用FOR子句指定要轉(zhuǎn)換的月份。

0