1

我想知道我将如何旋转下表

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
4

1 回答 1

1

如果你不介意用null0 代替,你可以使用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
于 2013-10-09T19:18:09.553 回答