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
     

Rotate Columns into Rows

 
Sales
Year Item Qty
2010 Pen 10
2010 Bag 20
2010 Cap 30
2011 Pen 40
2011 Bag 50
2011 Cap 60
2012 Pen 70
2012 Bag 80
2012 Cap 90
---- for Big Tables
SELECT Year = s.Year, SUM (CASE Item WHEN 'Pen' THEN Qty ELSE 0 END) as Pen, SUM (CASE Item WHEN 'Bag' THEN Qty ELSE 0 END) as Bag, SUM (CASE Item WHEN 'Cap' THEN Qty ELSE 0 END) as Pin FROM Sales s GROUP BY Year
---- for Small Tables
SELECT Year, Pen=ISNULL((SELECT Qty FROM Sales WHERE Item = 'Pen' AND YEAR = s.YEAR),0), Bag=ISNULL((SELECT Qty FROM Sales WHERE Item = 'Bag' AND YEAR = s.YEAR),0), Cap=ISNULL((SELECT Qty FROM Sales WHERE Item = 'Cap' AND YEAR = s.YEAR),0) FROM Sales s GROUP BY Year
Output
Year Pen Bag Cap
2010 10 20 30
2011 40 50 60
2012 70 80 90