假设有一个表格包含按月份组织的数值数据:
<code>MONTH | VALUE -------|------ 1 | 100 2 | 200 3 | 300 ...</code>
目标是将此数据转换为透视格式,从而更直观地查看月度值:
<code>MONTH_JAN | MONTH_FEB | MONTH_MAR | ... ---------|---------|---------| 100 | 200 | 300 | ...</code>
Oracle 11g 及更高版本引入了 PIVOT 运算符,可以轻松地进行数据透视。语法如下:
<code>SELECT * FROM table_name PIVOT ( aggregate_function(column_name) FOR (pivot_column) IN (list_of_values) );</code>
考虑以下示例数据:
<code>CREATE TABLE tq84_pivot ( month NUMBER, value NUMBER ); INSERT INTO tq84_pivot VALUES (1, 100), (2, 200), (3, 300), (4, 400), (5, 500), (6, 600); SELECT * FROM tq84_pivot PIVOT ( SUM(value) AS sum_value FOR (month) IN (1 AS month_jan, 2 AS month_feb, 3 AS month_mar, 4 AS month_apr, 5 AS month_mai, 6 AS month_jun, 7 AS month_jul, 8 AS month_aug, 9 AS month_sep, 10 AS month_oct, 11 AS month_nov, 12 AS month_dec) );</code>
结果如预期:
<code>MONTH_JAN | MONTH_FEB | MONTH_MAR | ... ---------|---------|---------| 100 | 200 | 300 | ...</code>
以上是如何在 Oracle SQL 中透视每月数据以便更轻松地进行分析?的详细内容。更多信息请关注PHP中文网其他相关文章!