<!-- https://learnsql.cpetoday.com/functions/m/table-pivot -->
# Table.Pivot

Language: Power Query M
Category: Table: headers and shape
Syntax: Table.Pivot(table as table, pivotValues as list, attributeColumn as text, valueColumn as text, optional aggregationFunction as nullable function) as table
Summary: Turns the values of one column into new column headers, filled with the values from another column.
Returns: A table with one column for each pivot value.
Level: Intermediate
Related: Table.Unpivot, Table.UnpivotOtherColumns, Table.Group, Table.Transpose

## What it does
Table.Pivot takes a long list, where each row holds one month and one value, and spreads the months across the top as columns. It produces the grid that a reader expects to see. Every column that is not used for the pivot becomes part of the row key, so the table should be cut down to the key columns first.

## Syntax and arguments
- **table**: the long table to pivot. Required.
- **pivotValues**: the list of values that become new columns, such as `List.Distinct(Long[Month])`. Required.
- **attributeColumn**: the column whose values become the new column headers, in quotes. Required.
- **valueColumn**: the column whose values fill the new columns, in quotes. Required.
- **aggregationFunction**: a function, such as `List.Sum`, used when more than one row falls in the same cell. Optional, but needed when duplicates can occur.

## Example
A general ledger has been summarized into one row per account and month. The months are spread across the top, with the net amount in each cell.

```powerquery
let
    Source = Excel.CurrentWorkbook(){[Name = "NetByMonth"]}[Content],
    Slim = Table.SelectColumns(Source, {"Account", "Month", "Net"}),
    Grid = Table.Pivot(Slim, List.Distinct(Slim[Month]), "Month", "Net", List.Sum)
in
    Grid
```

The Account column is the row key. Each distinct month becomes a column, and List.Sum adds up any amounts that share an account and a month.

## Things to watch
- Every column that is not the attribute or the value becomes part of the row key. Remove extra columns first, or the grid splits into more rows than you expect.
- The pivot values list decides the columns. A month added to the data later does not appear unless it is in the list. Building the list with List.Distinct from the data picks up new months automatically.
- Without an aggregation function, duplicate cells cause an error.
- Query folding: pivoting usually breaks folding, so it is normally done on the loaded data after the filters.

## In business terms
Budget versus actual grids, trial balances by period and sales by month are all pivoted layouts. Building them in the query gives a single, repeatable table that matches the report format.
