Tuesday, February 26, 2013

Alternative to PIVOT

Today i have faced a problem with pivot element. Actually i want apply inner join of a record set of one table say Q1 with a query after applying pivot on it say Q2.

I know there will be a way out to it but i found a another way to show the result that somehow pivot performs.

Table: Category
Query 1: select * from category
Result1:
CatName      AlbumImage
   Jazz           img1.png
   Pop           img2.png
  Hindi          img3.png

Here is the query
Query 2:
SELECT

MIN(CASE catname WHEN 'Jazz' THEN AlbumImage ELSE NULL END) as Jazz,
MIN(CASE catname WHEN 'Pop' THEN AlbumImage ELSE NULL END) as Pop,
MIN(CASE catname WHEN 'Hindi' THEN AlbumImage ELSE NULL END) as Hindi
FROM category
Result 2:
This will show the records like this
Jazz              Pop            Hindi
img1.png      img1.png      img1.png


Applying Inner join
Now you can use this Query 2 in some inner join like this.
Query 3:
select q2.jazz,q2.pop,q2,hindi,q1.price from
(
         select id, price from table 2
) as q1,
left outer join
(

        SELECT id,

        MIN(CASE catname WHEN 'Jazz' THEN AlbumImage ELSE NULL END) as Jazz,
        MIN(CASE catname WHEN 'Pop' THEN AlbumImage ELSE NULL END) as Pop,
        MIN(CASE catname WHEN 'Hindi' THEN AlbumImage ELSE NULL END) as Hindi
        FROM category
) as q2


on q1.id=q2.id

I hope this will help you in any way. My emphasis was to show an alternative method which i too found from somewhere else and it help me.

Using Pivot

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