Tuesday, 12 May 2015

Pivot table


 

DECLARE @columns VARCHAR(1000)    

SELECT @columns = COALESCE(@columns + ',[' + cast(Status as varchar) + ']','[' + cast(Status as varchar)+ ']')       
FROM(           
  Select Status From Statuses          
) x     
     
print @columns

DECLARE @query nVARCHAR(4000)     

SET @query = ';with CTE_Result as
(
      select Applications.AppName,Computers.Status
      from Applications
      left join Installations on Installations.AppID = Applications.AppID
      left join Computers on Computers.HostID = Installations.HostID
      WHere AppName=''Adobe AIR''
      --group by Applications.AppName,Computers.Status
)
SELECT * FROM
(
      SELECT * from CTE_Result
) as S PIVOT
( COUNT(Status) FOR [Status] IN ('+ @columns + ')) AS PivotTable'
 print @columns    
EXECUTE(@query)    


Result is 

 

No comments:

Post a Comment