Learn T-SQL Commands with Samples
Skip Navigation Links
Skip Navigation Links.
Expand DatabaseDatabase
Expand TableTable
Expand ViewView
Expand Stored ProcedureStored Procedure
Expand Data FilteringData Filtering
Expand Data GroupingData Grouping
Expand JoinsJoins
Expand TriggerTrigger
Expand CursorCursor
Expand OperatorsOperators
Expand ConstraintsConstraints
Expand FunctionsFunctions
Expand Conditional ProcessingConditional Processing
Expand LoopingLooping
Expand Error HandlingError Handling
Collapse v.IMP Queriesv.IMP Queries
Expand XMLXML
Expand Query PerformanceQuery Performance
Expand QueriesQueries
Expand NormalizationNormalization
Expand CreateCreate
     

PIVOT and UNPIVOT Data

 
      
Sales
OrderID Item Qty
1 Books 30
1 Pens 40
2 Books 100
2 Pens 200
3 Bags 9
---- How to PIVOT Data
SELECT * FROM ( SELECT * FROM Sales ) AS source PIVOT ( SUM(Qty) FOR Item IN (Books, Pens, Bags) ) as pvt
Output
OrderID Books Pens Bags
1 30 40 NULL
2 100 200 9
---- How to UNPIVOT Data
SELECT * FROM ( SELECT * FROM Sales1 ) p UNPIVOT ( Qty FOR Item IN(Books, Pens, Bags) ) as unpvt