MySQL 行列转换

原料:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
create table t_score
(
  name varchar(20) ,
  subject varchar(20),
  score float
)INSERT INTO `t_score` VALUES
    ('王海', '语文', '86'),
    ('王海', '数学', '83'),
    ('王海', '英语', '93'),
    ('陶俊', '语文', '88'),
    ('陶俊', '数学', '84'),
    ('陶俊', '英语', '94'),
    ('刘可', '语文', '80'),
    ('刘可', '数学', '86'),
    ('刘可', '英语', '88'),
    ('李春', '语文', '89'),
    ('李春', '数学', '80'),
    ('李春', '英语', '87');

 查询表的数据

  select * from t_score;

要求实现的效果

实现方法:

复制代码
select name 名字,
       max(case subject
             when '语文' then score end) '语文',
       max(case subject
             when '数学' then  score end) '数学',
       max(case subject
             when '英语' then score end) '英语',
       sum(mark) score
from t_score
group by name;

# case subject when '语文' then score end
# 如果 subject 的值为 语文 时 取得相对应 的 成绩值
# max( case subject when '语文' then score end)取得最大的值。
# 因为 使用 case subject when '语文' then score end 时 会生成 三条数据
#比如:
# 语文 数学 英语
# 80 null null

# title = subject,mark = score(懒得换字段名了。)

 





结果:
复制代码

 

再查他们所有语文、数学、英语 成绩的合计

复制代码
select
       'TOTAL',
        sum(case subject when '语文' then score end),
        sum(case subject when '数学' then score end),
        sum(case subject when '英语' then score end),
        sum(score)
from t_score

结果:
复制代码

 合起来:

复制代码
select
       name 名字,
       case subject when '语文' then score end '语文',
       max(case subject when '数学' then score end) '数学',
       max(case subject when '英语' then score end) '英语',
       sum( score ) score
from t_score group by name
union all
select
       'TOTAL',
        sum(case subject when '语文' then score end),
        sum(case subject when '数学' then score end),
        sum(case subject when '英语' then score end),
        sum( score )
from t_score;

结果:

复制代码

 

posted @   追梦滴小蜗牛  阅读(1697)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· Vite CVE-2025-30208 安全漏洞
· 《HelloGitHub》第 108 期
· MQ 如何保证数据一致性?
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
点击右上角即可分享
微信分享提示