PIVOT 操作实现方式
时间: 2024-03-06 17:49:29 浏览: 85
在 SQL Server 中,可以使用 PIVOT 关键字来实现数据透视,其基本语法如下:
```
SELECT <non-pivoted column>,
[<first pivoted column>] AS <column name>,
[<second pivoted column>] AS <column name>,
...
FROM
(<SELECT query that produces the data>)
AS <alias for the source data>
PIVOT
(
<aggregation function>(<value column>)
FOR
[<pivoted column>]
IN ( [first pivoted column], [second pivoted column],
... ,[last pivoted column])
) AS <alias for the pivot table>
```
其中,<non-pivoted column> 表示不需要透视的列,<first pivoted column>、<second pivoted column> 等表示需要透视的列,<column name> 表示透视后的列名,<aggregation function> 表示聚合函数,<value column> 表示需要聚合的值列,<pivoted column> 表示需要透视的列,IN 子句中指定透视后的列名。
在 Oracle 中,可以使用 PIVOT 操作符来实现数据透视,其基本语法如下:
```
SELECT *
FROM
(<SELECT query that produces the data>)
PIVOT
(
<aggregation function>(<value column>)
FOR
[<pivoted column>]
IN ( [first pivoted column], [second pivoted column],
... ,[last pivoted column])
)
```
在 MySQL 中,可以使用 GROUP_CONCAT 函数来实现数据透视,其基本语法如下:
```
SELECT <non-pivoted column>,
GROUP_CONCAT(CASE WHEN <pivoted column> = '<first pivoted column>' THEN <value column> END) AS '<first pivoted column>',
GROUP_CONCAT(CASE WHEN <pivoted column> = '<second pivoted column>' THEN <value column> END) AS '<second pivoted column>',
...
FROM
(<SELECT query that produces the data>)
AS <alias for the source data>
GROUP BY <non-pivoted column>
```
需要注意的是,不同的数据库系统在实现 PIVOT 操作时可能存在一些细微的差异,具体的语法和实现方式可能会有所不同。
阅读全文