简体   繁体   中英

How to transform rows in Columns with Cube, Pivot or Rollup SQL

I have a table with this information:

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

I would like to show like that

  code    2015    2016  2017
    123    12      16    14

Can you help me please? Thanks

One way is using conditional aggregation:

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

Or using PIVOT :

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

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM