Mid Detailed answer PIVOT SQL & Databases

How do you pivot rows to columns in SQL Server?

Short answer: Use PIVOT with aggregate + IN list of column values, or conditional aggregation with CASE (more portable and flexible).

Sample solution

T-SQL
-- Conditional aggregation (often preferred)
SELECT CustomerId,
       SUM(CASE WHEN Year = 2024 THEN Amount ELSE 0 END) AS Y2024,
       SUM(CASE WHEN Year = 2025 THEN Amount ELSE 0 END) AS Y2025
FROM Sales
GROUP BY CustomerId;

-- PIVOT operator
SELECT CustomerId, [2024], [2025]
FROM (SELECT CustomerId, Year, Amount FROM Sales) src
PIVOT (SUM(Amount) FOR Year IN ([2024], [2025])) p;
CASE aggregation is easier when pivot columns are dynamic.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details