COMPUTER ENGINEER

Jump to examples
Blog
SQL Server / T-SQL6 min study
58/ 65

Data engineering

PIVOT, UNPIVOT and conditional aggregation

Preserve grain while reshaping a report.

UnderstandStudy an examplePractise

Understand the concept

PIVOT turns chosen values into columns and applies aggregation. Extra source columns can create unexpected implicit grouping. Prepare only the grouping key, pivot key and measure. Conditional CASE aggregation is often clearer and more flexible.

UNPIVOT turns columns into rows and discards NULL values. Dynamic pivoting creates an identifier list, requiring approved names, QUOTENAME and safe value parameters. These examples use fixed Paid/Pending/Cancelled statuses. Zero and missing-data NULL differ, though showing zero in a count report can be a deliberate reporting choice.

WHEN TO USE IT

Prepare dashboard columns and long-form data.

COMMON PITFALL

Leaving irrelevant columns in a PIVOT source.

01 / PRACTICE

One topic. Three levels of depth.

T-SQL / SQL Server 2019+
SELECT CustomerId, SUM(CASE WHEN Status = 'Paid' THEN 1 ELSE 0 END) AS Paid FROM lab.SalesOrder GROUP BY CustomerId;

Uses explicit conditional aggregation.

This page does not execute SQL. Practise in the downloadable SqlStudioLab using SSMS. Before rerunning temporary-table examples, remove only the relevant #table. Views, procedures and functions create persistent lab objects; never use a production connection.

02 / YOUR TURN

Try it yourself first.

Count Paid and Pending orders per customer using CASE.

Show the solution and explanation
Worked solution
SELECT CustomerId, SUM(CASE WHEN Status = 'Paid' THEN 1 ELSE 0 END) AS Paid, SUM(CASE WHEN Status = 'Pending' THEN 1 ELSE 0 END) AS Pending FROM lab.SalesOrder GROUP BY CustomerId;

Cancelled rows belong to groups but do not increase these measures.