Convert Row data in column using Sql Server



What is pivot ?

Pivot  is   Relational   operator in SQL server  which is used to convert data from Row to Column view. To convert data from Column to Row we will use Unpivot Operator .Unpivot is opposite to Pivot

So lets See how we will use It.We have Data like this in Table




     
    EmployeeID EmployeeName Country State

         14 John D India Karnataka
         15 John R India Bihar
         16 John G India Maharastra
         17 John P India UP


We will use Pivot For State



   select [Karnataka],[Bihar],[Maharastra],[UP]  from(

   select EmployeeName,state from Tablename
   )t
  pivot( max(EmployeeName)  for state in ( [Karnataka],[Bihar],[Maharastra],[UP])  )st



This will convert Row data in Sates to Column with value EmployeeName
So the Result Will be Like

   
    Karnataka   Bihar   Maharastra    UP

    John D          John R    John G           John P


No comments:

Post a Comment