sqlserver 的PIVOT 函数
时间: 2023-08-14 08:05:52 浏览: 236
SQL Server的PIVOT函数用于将行数据转换为列数据,将某一列的值作为列名,然后将其他列的值填充到相应的列中。
使用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 query>
PIVOT
(
<aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
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]`等是需要转置的列名。`<aggregation function>`是用于聚合的函数,如SUM、COUNT等。
以下是一个示例,演示如何使用PIVOT函数将行数据转换为列数据:
```
SELECT *
FROM
(
SELECT CustomerID, ProductName, Quantity
FROM Sales
) AS SalesData
PIVOT
(
SUM(Quantity)
FOR ProductName
IN ([ProductA], [ProductB], [ProductC])
) AS PivotTable;
```
上述示例中,Sales表包含了CustomerID、ProductName和Quantity三列数据。使用PIVOT函数将ProductName列的值转置为列名,然后将Quantity列的值填充到相应的列中,最后得到一个以CustomerID为主键的透视表。
希望以上信息对您有所帮助!如果您有任何其他问题,请随时提问。
阅读全文