[英]Pivoting data - SQL Server 2008
我想知道如何旋轉下表
id | name | course | participating | year
-----------------------------------------------------------------
abc | harv | math | 4 | 2012
abc | harv | eng | 2 | 2012
abc | harv | hist | 3 | 2011
eee | yale | eng | 2 | 2012
eee | yale | math | 5 | 2012
ppp | mit | hist | 7 | 2011
ppp | mit | eng | 4 | 2012
看起來像這樣:
id | name | year | math | eng | hist
-------------------------------------------------------
abc | harv | 2011 | 0 | 0 | 3
abc | harv | 2012 | 4 | 2 | 0
eee | yale | 2012 | 5 | 2 | 0
ppp | mit | 2011 | 0 | 0 | 7
ppp | mit | 2012 | 0 | 4 | 0
如果您不介意null
而不是0,則可以使用pivot
關鍵字:
select *
from @temp
pivot (max(participating) for course in ([math], [eng], [hist])) as p
id name year math eng hist
----------------------------------------
abc harv 2011 NULL NULL 3
abc harv 2012 4 2 NULL
eee yale 2012 5 2 NULL
ppp mit 2011 NULL NULL 7
ppp mit 2012 NULL 4 NULL
否則,您可以手動進行數據透視:
select
id, name, [year],
isnull(max(case when course = 'math' then participating end), 0) as [math],
isnull(max(case when course = 'eng' then participating end), 0) as [eng],
isnull(max(case when course = 'hist' then participating end), 0) as [hist]
from @temp
group by id, name, [year]
id name year math eng hist
----------------------------------------
abc harv 2011 0 0 3
abc harv 2012 4 2 0
eee yale 2012 5 2 0
ppp mit 2011 0 0 7
ppp mit 2012 0 4 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.