当前位置: 代码迷 >> SQL >> 一起转列sql题
  详细解决方案

一起转列sql题

热度:84   发布时间:2016-05-05 13:59:52.0
一行转列sql题
有样本数据abc表如下:
id       name        score
1        se          30
2        se          40
3        se          58
1        hn          65
2        hn          47
3       hn          50
想转化成如下表样式:
表名:abc
     name        score1  score2  score3 
      se            30          40          58
      hn            65          47         50


sql1
select b.name,sum(b.score1) score1,sum(b.score2) score2,sum(b.score3) score3from (    select a.name,    case when id=1 then score else 0 end score1,    case when id=2 then score else 0 end score2,    case when id=3 then score else 0 end score3    from abc a    ) bgroup by b.name

sql2:
select name, sum(case when id=1 then score else 0 end) score1,sum(case when id=2 then score else 0 end) score2,sum(case when id=3 then score else 0 end) score3 from abc group by name

select a.name,a.score,a1.score,a2.scorefrom abc a,abc a1,abc a2where a.name=a1.name and a.id =1 and a.name=a2.nameand a1.id = 2 and a2.id=3
  相关解决方案