SQL Server › Pivoting & Unpivoting Data
What are some practical, real world use cases where PIVOT and UNPIVOT are commonly applied in business reporting?
IntermediateAnswer
PIVOT is commonly used to turn monthly, quarterly, or yearly data into side by side columns for trend comparison reports, survey response summaries showing counts per answer choice as columns, and inventory reports showing stock levels across different warehouse locations, while UNPIVOT is often used when importing spreadsheet style data that needs to be normalized back into a proper row based format for storage.
-- Survey results pivoted to show response counts per answer choice
SELECT QuestionId, [Yes], [No], [Maybe]
FROM SurveyResponses
PIVOT (COUNT(ResponseId) FOR Answer IN ([Yes], [No], [Maybe])) AS pvt;Real-world example A customer feedback system pivots survey response data to show the count of yes, no, and maybe answers as separate columns for each question, making it easy for stakeholders to quickly compare responses across many questions at once.