有这样一张横表A
name | course | score |
小明 | 英语 | 64 |
小明 | 语文 | 45 |
小明 | 数学 | 43 |
小红 | 英语 | 34 |
小红 | 语文 | 76 |
小红 | 数学 | 56 |
需要转换成如下B表:
name | 语文 | 数学 | 英语 |
小明 | 45 | 43 | 64 |
小红 | 76 | 56 | 34 |
这里主要考察 case when的用法
select name,sum(case when course='语文' then score else 0 end),
sum(case when course='英语' then score else 0 end),
sum(case when course='数学' then score else 0 end)
from A
group by name
如果是B表转换为A表
主要考察union all用法
select name,'语文' as course,语文 as score from B
union all
select name,'数学' as course,数学 as score from B
union all
select name,'英语' as course,英语 as score from B