本查询的目标是将按行组织的数据转换为列,其中每一列代表输入行中的特定值。
考虑以下表格:
月份 | 数值 |
---|---|
1 | 100 |
2 | 200 |
3 | 300 |
4 | 400 |
5 | 500 |
6 | 600 |
我们的目标是将数据透视,以便输出表如下所示:
一月 | 二月 | 三月 | 四月 | 五月 | 六月 |
---|---|---|---|---|---|
100 | 200 | 300 | 400 | 500 | 600 |
从 Oracle 11g 开始,PIVOT 操作符提供了一种直接的方法来实现这一点:
<code class="language-sql">CREATE TABLE tq84_pivot ( month NUMBER, value NUMBER ); INSERT INTO tq84_pivot VALUES(1, 100); INSERT INTO tq84_pivot VALUES(2, 200); INSERT INTO tq84_pivot VALUES(3, 300); INSERT INTO tq84_pivot VALUES(4, 400); INSERT INTO tq84_pivot VALUES(5, 500); INSERT INTO tq84_pivot VALUES(6, 600); -- 插入额外的行以进行演示 INSERT INTO tq84_pivot VALUES(1, 400); INSERT INTO tq84_pivot VALUES(2, 350); INSERT INTO tq84_pivot VALUES(4, 150); 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>
此查询使用带有 'FOR' 子句的 PIVOT 操作符来指定透视列和关联值。通过按 'month' 列分组数据并使用 SUM() 聚合 'value' 列,我们获得了所需的输出,其中每个月份都有其对应的值。
以上是如何使用 Oracle SQL 的 PIVOT 运算符将行数据转换为列?的详细内容。更多信息请关注PHP中文网其他相关文章!