unpivot 操作符將 oracle 中的行數(shù)據(jù)轉(zhuǎn)換為列數(shù)據(jù),用于更易于分析和查詢(xún)。它將包含多個(gè)行列的數(shù)據(jù)集轉(zhuǎn)換為一個(gè)帶有 id 列和值列的新數(shù)據(jù)集,其中 id 列表示原始行,值列包含原始列中的值。unpivot 語(yǔ)法為:select * from unpivot(table_name) as unpivoted_table[where pivot_condition]。其優(yōu)點(diǎn)包括簡(jiǎn)化查詢(xún)、提高性能和支持?jǐn)?shù)據(jù)透視。例如,可以將銷(xiāo)售季度數(shù)據(jù)轉(zhuǎn)換為列,以便根據(jù)產(chǎn)品和季度輕松分析銷(xiāo)售額。
Oracle 中的 UNPIVOT 用法
UNPIVOT 是什么?
UNPIVOT 是一種 Oracle 操作符,用于將行數(shù)據(jù)轉(zhuǎn)換為列數(shù)據(jù)。它將一個(gè)包含多行、多列的數(shù)據(jù)集轉(zhuǎn)換為一個(gè)包含兩列的新數(shù)據(jù)集:一個(gè) ID 列(表示原始行)和一個(gè)值列(包含原始列中的值)。
UNPIVOT 用法
UNPIVOT 語(yǔ)法如下:
<code>SELECT * FROM UNPIVOT(table_name) [AS unpivoted_table] [FOR column_name IN (column_list)] [WHERE pivot_condition]</code>
登錄后復(fù)制
其中:
table_name 是要轉(zhuǎn)換的數(shù)據(jù)集的名稱(chēng)。
column_name 是要轉(zhuǎn)換為列的原始列的名稱(chēng)。
column_list 是要轉(zhuǎn)換為列的原始列的列表。
pivot_condition 是可選的條件,用于過(guò)濾要轉(zhuǎn)換為列的數(shù)據(jù)。
示例
假設(shè)有一個(gè)名為 sales 的數(shù)據(jù)集,其中包含以下列:
product_id
product_name
sales_q1
sales_q2
sales_q3
sales_q4
要將銷(xiāo)售季度數(shù)據(jù)轉(zhuǎn)換為列,可以使用以下 UNPIVOT 查詢(xún):
<code>SELECT * FROM UNPIVOT(sales) AS unpivoted_sales FOR sales_quarter IN (sales_q1, sales_q2, sales_q3, sales_q4)</code>
登錄后復(fù)制
結(jié)果數(shù)據(jù)集將如下所示:
| product_id | product_name | sales_quarter | sales_value |
|---|---|---|---|
| 1 | Product A | Q1 | 100 |
| 1 | Product A | Q2 | 200 |
| 1 | Product A | Q3 | 300 |
| 1 | Product A | Q4 | 400 |
| 2 | Product B | Q1 | 500 |
| 2 | Product B | Q2 | 600 |
| 2 | Product B | Q3 | 700 |
| 2 | Product B | Q4 | 800 |
UNPIVOT 的優(yōu)點(diǎn)
使用 UNPIVOT 有以下優(yōu)點(diǎn):
將行數(shù)據(jù)轉(zhuǎn)換為更易于分析的列數(shù)據(jù)。
簡(jiǎn)化查詢(xún)和報(bào)告設(shè)計(jì)。
提高數(shù)據(jù)聚合和透視表的性能。






