PIVOT is used to rotate rows into columns.
Think of it as converting vertical data into horizontal data for reporting or analytics.
1.Why use PIVOT?
- Makes aggregated data easier to read
- Useful for cross-tab reports
- Reduces the need for multiple CASE statements
2.Basic Syntax
3.Example Table: Sales
| Year | Region | Amount |
|---|---|---|
| 2024 | East | 1000 |
| 2024 | West | 1500 |
| 2025 | East | 2000 |
| 2025 | West | 2500 |
4.Pivot: Year as Row, Region as Columns
Result
| Year | East | West |
|---|---|---|
| 2024 | 1000 | 1500 |
| 2025 | 2000 | 2500 |
✅ Rows are now rotated into columns.
5.Pivot with Multiple Aggregates
SQL Server PIVOT only allows one aggregate per pivot, so for multiple aggregates, you need multiple pivot statements or CASE expressions.
6.Dynamic Pivot (Optional)
If column values are unknown, you can generate pivot columns dynamically using dynamic SQL:
7.Pivot vs CASE Statement
CASE Example:
