Skip to content

PIVOT

PIVOT(aggregate_function(column_to_aggregate)FOR column_to_transformIN (list_of_values))

Section titled “PIVOT(aggregate_function(column_to_aggregate)FOR column_to_transformIN (list_of_values))”
  • aggregate_function(column_to_aggregate): This represents the aggregate function, such as COUNT, SUM, AVG, MIN, MAX, etc., applied onto the column that needs to be aggregated.
  • column_to_transform: This identifies the column in the original table that will be transformed or pivoted into the columns of the final, pivoted table.
  • list_of_values: This refers to the unique values in the column_to_transform which will become the new column headers in the final, pivoted table.
SELECT Store, [2018], [2019], [2020]
FROM (
SELECT Store, Year, Sales
FROM SalesData
) AS SourceTable
PIVOT (
SUM(Sales)
FOR Year IN ([2018], [2019], [2020])
) AS PivotTable;
| Store | 2018 | 2019 | 2020 |
|-------|------|------|------|
| A | 100 | 120 | 150 |
| B | 200 | 180 | 210 |
| C | 300 | 320 | 350 |

The provided SQL script performs a pivot operation on the SalesData source table, which transforms rows into columns. Here, SUM of sales is being calculated for each year (2018, 2019, 2020) across each Store. The pivot table in the output shows sales data for the stores across different years.