liveBook · Manning

Pivoting

As explained in 100 SQL Server Mistakes and How to Avoid Them

The PIVOT operator transforms grouped row values into columns while applying an aggregation to associated values.

Pivoting transforms grouped row values into columns while aggregating associated values. For a stock report, it turns product categories from vertical rows into one horizontal result. Mistake #1: using a cursor because the output columns appear to require row-by-row updates. Cursors impose repeated statement overhead and are inefficient for relational data, especially at large row counts. section 5.7

Prefer a set-based PIVOT query when the report has known category columns:

  • Avoid cursor-based temporary-table updates unless a specific constraint proves necessary; the set-based form is shorter and avoids per-row processing. section 5.7

MagicChoc stock report

A stock query groups product categories and feeds ProductCategoryName and Stock into PIVOT, producing columns such as Raw Ingredients, Machine Parts, and Misc with summed quantities.

How 100 SQL Server Mistakes and How to Avoid Them covers it

How deep it goes
Shows the source query, aggregate, and explicit output-column list, while contrasting the result with cursor implementation and cost.
Examples
Uses MagicChoc product stock, named category columns, and equivalent cursor and PIVOT implementations.
What it assumes
Assumes grouped rows, joins, and aggregate functions; demonstrates the source-to-PIVOT transformation through a stock-report example.
What you can do after
Apply it via T-SQL PIVOT to build grouped horizontal reports without row-by-row cursor updates.
How it connects
Connects PIVOT with aggregation, cursors, temporary tables, joins, and grouped queries.

Also explained in

Compare how 2 books explain pivoting →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 SQL Server Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.