Pivot is used for making your values in various columns into a single row. It actually rotates the values from column into multiple coluns
Here is a simple example which will show how we can use the pivot element.
Table : Category
Before
CatName CatID
Jazz 1
Pop 2
Hindi 3
English 4
Instrumental 5
Punjabi 6
Now Applying Pivot on this
SELECT [Jazz],[Pop],[Hindi],[English] from --Desired Coluns
(
SELECT catname,catid FROM category --Main Query
) as q1 --Alias query 1
PIVOT
(
MIN(q1.catid)--Function (Aggregation)
FOR catname in ([Jazz],[Pop],[Hindi],[English])--Values specified of column
) as pivotq1
After applying it will convert into
After
Jazz Pop Hindi English
1 2 3 4
When you have to show the text values then you can use MIN function. Other functions like AVG ,COUNT ,SUM will not show the values instead they will apply functions on data. MIN ,MAX will show you the text values
MSDN shows a excellent examples and syntax Click here to view it
No comments:
Post a Comment