Thursday, July 11, 2013

sql pivot query

 IF @OperationId=3
       BEGIN 
      
     --  Declare @district_Name varchar(50)='Sanand'
        Declare @ActYrs varchar(20)
        Set @ActYrs=(Select ActiveYear from LevelControl
        Where ControlId=1 and (Level_1=1 or Level_2=1 or Level_3=1))
        Select *   into #TempLeve9
        From
        (Select Category,Candidates,ActiveYear,district ,CandidateClass from RuleSetFilter) as p
        PIVOT
        (
            sum(Candidates) for Category In([M & HCV Key Acc Customer],[M & HCV Other],[LCV],[SCV-Ace],[SCV-Magic])
        ) as pvt
       
        Where ActiveYear=@ActYrs AND district=@district_Name
        Order By  pvt.district   
       
      --======================================================================================
 
        Select district ,Present_Class_In_School,[M & HCV Key Acc Customer] as 'M & HCV Key Acc Customer1' ,[M & HCV Other] as 'M & HCV Other1' ,[LCV] as 'LCV1' ,[SCV-Ace] as 'SCV-Ace1' ,[SCV-Magic] as 'SCV-Magic1' into #TempLevel0
        From
        (Select COUNT( a.[Lev0Id]) as 'Totpp', a.Vehicle_Category , b.district , a.Present_Class_In_School from Level0Data  as a inner join RuleSetFilter as b
            on a.Vehicle_Category=b.Category 
            Where a.district_id=(select district_id from tbl_mst_district where district_name=@district_Name)
        group by Vehicle_Category , b.district , a.Present_Class_In_School) as d
        PIVOT
        (
            sum(Totpp)  for Vehicle_Category   In([M & HCV Key Acc Customer],[M & HCV Other],[LCV],[SCV-Ace],[SCV-Magic])
        )as pvt
  
  --select * from #TempLevel0
  --select * from #TempLeve9
  --drop table  #TempLevel0
  --drop table #TempLeve9
 
 
  select #TempLeve9.district as district ,
  #TempLeve9.[M & HCV Key Acc Customer],
  #TempLeve9.[SCV-Ace] ,
  #TempLeve9.[M & HCV Other],
  #TempLeve9.[SCV-Magic],
  #TempLeve9.[LCV],
  #TempLeve9.[ActiveYear],
  #TempLeve9.[CandidateClass],
  #TempLevel0.[M & HCV Key Acc Customer1],
  #TempLevel0.[SCV-Ace1] ,
  #TempLevel0.[M & HCV Other1],
  #TempLevel0.[SCV-Magic1],
  #TempLevel0.[LCV1]
 
 
   from    #TempLeve9 left join #TempLevel0 
  on #TempLeve9.district=#TempLevel0.district
  AND #TempLeve9.CandidateClass=#TempLevel0.Present_Class_In_School
 
 
 
    END

No comments:

Post a Comment