透视数据 - SQL Server 2008

时间:2013-10-09 19:01:34

标签: sql sql-server-2008 pivot

我想知道如何转动下表

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

1 个答案:

答案 0 :(得分:1)

如果您不介意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