2017-10-19 147 views
1

我試試這個總樞軸在SQL Server

declare @t as table (yea int, rating varchar(100)) 

insert into @t 
values (2012, 'US'), (2013, 'S'), (2014, 'G'), 
     (2015, 'E'), (2016, 'E')  

--select * from @T 

select 
    [2012], [2013], [2014], [2015], [2016] 
from 
    (select rating 
    from @T) p 
pivot 
    (max (rating) 
    for rating in ([2012], [2013], [2014], [2015], [2016])) as pb 

,我得到了這樣的結果:

2012 2013 2014 2015 2016 
-------------------------------------- 
NULL NULL NULL NULL NULL 

,但我真的很喜歡這樣的結果,而不是:

2012 2013 2014 2015 2016 
------------------------------------- 
US  S  G  E  E 

這是空數據,因爲max(rating)?如果是這樣 - 我如何獲得所需的數據?

回答

0

你失蹤(不知道是啊,是一個錯字,所以我離開它是)

declare @t as table (yea int, rating varchar(100)) 
     insert into @t values (2012,'US')  
     insert into @t values (2013,'S')     
     insert into @t values (2014,'G') 
     insert into @t values (2015,'E')   
     insert into @t values (2016,'E')   
     --select * from @T 
     select [2012],[2013],[2014],[2015],[2016] 
      from 
      (select yea,rating 
      from @T 
      ) p 
      pivot 
      (max (rating) for yea in ([2012],[2013],[2014],[2015],[2016])) as pb 

返回

2012 2013 2014 2015 2016 
US  S  G  E  E