pivot in SQL
时间: 2023-09-23 21:08:39 浏览: 79
A pivot in SQL is a way of transforming data from a long format to a wide format, where the rows are turned into columns. This is done using the PIVOT operator, which is used to aggregate and summarize data based on certain criteria.
For example, let's say we have a table of sales data that looks like this:
| Region | Product | Sales |
|--------|---------|-------|
| East | A | 100 |
| East | B | 200 |
| West | A | 150 |
| West | B | 250 |
If we want to pivot this data to show the total sales for each region and product, we can use the PIVOT operator like this:
SELECT Region, [A], [B]
FROM (
SELECT Region, Product, Sales
FROM SalesData
) AS SourceTable
PIVOT (
SUM(Sales)
FOR Product IN ([A], [B])
) AS PivotTable;
This will give us a table that looks like this:
| Region | A | B |
|--------|-------|-------|
| East | 100 | 200 |
| West | 150 | 250 |
In this example, the PIVOT operator has transformed the data so that the rows have become columns, with the Sales values for each Product being aggregated and summarized for each Region.
阅读全文