如何使用Cube,Pivot或Rollup SQL转换列中的行

时间:2017-05-12 17:58:21

标签: sql sql-server

我有一张包含此信息的表格:

code    score    quality
123     2015      12
123     2016      16    
123     2017      14

我想像那样展示

  code    2015    2016  2017
    123    12      16    14
你能帮帮我吗?感谢

1 个答案:

答案 0 :(得分:4)

一种方法是使用条件聚合:

select code,
    max(case when score = 2015 then quality end) as [2015],
    max(case when score = 2016 then quality end) as [2016],
    max(case when score = 2017 then quality end) as [2017]
from your_table
group by code;

Demo

或使用PIVOT

select *
from your_table
pivot (
    max(quality) for score in ([2015],[2016],[2017])
) p;

Demo