MySQL的行列转换

MySQL的行列转换

MySQL的行列转换的写法, 如果有需要可以参考下

现在如下有两个表:

成绩表(t_score)

idsubjectidscore
1195
2285
3390
4488
5598
6689
7790
8888
9987

科目表(t_subject)

idsubject
1语文
2数学
3英语
4物理
5化学
6生物
7政治
8历史
9地理

想要转成如下的表:

id语文数学英语物理化学生物政治历史地理
1958590889889908887

中间代码

select 
    CONCAT("  sum(case when j.`subject`='",`subject`,"' then s.score end) as '",`subject`,"',") as tempcode
from t_subject

查询结果

tempcode
sum(case when j.subject=’语文’ then s.score end) as ‘语文’,
sum(case when j.subject=’数学’ then s.score end) as ‘数学’,
sum(case when j.subject=’英语’ then s.score end) as ‘英语’,
sum(case when j.subject=’物理’ then s.score end) as ‘物理’,
sum(case when j.subject=’化学’ then s.score end) as ‘化学’,
sum(case when j.subject=’生物’ then s.score end) as ‘生物’,
sum(case when j.subject=’政治’ then s.score end) as ‘政治’,
sum(case when j.subject=’历史’ then s.score end) as ‘历史’,
sum(case when j.subject=’地理’ then s.score end) as ‘地理’,

最终转换代码

select s.`id`,
  sum(case when j.`subject`='语文' then s.score end) as '语文',
  sum(case when j.`subject`='数学' then s.score end) as '数学',
  sum(case when j.`subject`='英语' then s.score end) as '英语',
  sum(case when j.`subject`='物理' then s.score end) as '物理',
  sum(case when j.`subject`='化学' then s.score end) as '化学',
  sum(case when j.`subject`='生物' then s.score end) as '生物',
  sum(case when j.`subject`='政治' then s.score end) as '政治',
  sum(case when j.`subject`='历史' then s.score end) as '历史',
  sum(case when j.`subject`='地理' then s.score end) as '地理'
from t_score s inner join t_subject j on s.subjectid=j.`id`

查询结果就是上面的结果, 就不再贴出了.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值