sql里面pivot函数怎么用,举个例子
时间: 2023-05-19 09:04:07 浏览: 157
SQL基础教程之行转列Pivot函数
Pivot 函数可以将行数据转换为列数据,可以使用以下语法:
SELECT *
FROM (
SELECT [列1], [列2], [值]
FROM [表名]
) AS [源表]
PIVOT (
[聚合函数]([值])
FOR [列名] IN ([列1], [列2], ...)
) AS [结果表]
例如,假设有一个表格名为 Sales,包含以下数据:
| Region | Product | Sales |
|--------|---------|-------|
| East | Apple | 100 |
| East | Banana | 200 |
| West | Apple | 150 |
| West | Banana | 250 |
我们可以使用 Pivot 函数将其转换为以下形式:
| Region | Apple | Banana |
|--------|-------|--------|
| East | 100 | 200 |
| West | 150 | 250 |
具体的 SQL 语句如下:
SELECT *
FROM (
SELECT Region, Product, Sales
FROM Sales
) AS SourceTable
PIVOT (
SUM(Sales)
FOR Product IN (Apple, Banana)
) AS PivotTable
阅读全文