简单例子 数据结构如下

use dataTest
create table t_score
(
    name varchar(24) ,
    subject varchar(24),
    grade double(5,2)
)

INSERT INTO `t_score` VALUES
    ('王海', '语文', 86),
    ('王海', '数学', 83),
    ('王海', '英语', 93),
    ('陶俊', '语文', 88),
    ('陶俊', '数学', 84),
    ('陶俊', '英语', 94),
    ('刘可', '语文', 80),
    ('刘可', '数学', 86),
    ('刘可', '英语', 88),
    ('李春', '语文', 89),
    ('李春', '数学', 80),
    ('李春', '英语', 87);

select name,
sum(case when subject = '语文' then grade end) as Chiese, 
sum(case when subject = '数学' then grade end) as Math, 
sum(case when subject = '英语' then grade end) as English,
sum(grade) as score
from t_score group by name
union 
select 'TOTAL',
sum(case when subject = '语文' then grade end) as Chiese, 
sum(case when subject = '数学' then grade end) as Math, 
sum(case when subject = '英语' then grade end) as English,
sum(grade) as score
from t_score

#第二种方式
select name as Name,
sum(IF(subject = '语文',grade,0))Chiese,
sum(IF(subject = '数学',grade,0))Math,
sum(IF(subject = '英语',grade,0))English,
sum(grade)score
 from t_score GROUP BY name
UNION ALL
select 'TOTAL',
sum(IF(subject = '语文',grade,0))Chiese,
sum(IF(subject = '数学',grade,0))Math,
sum(IF(subject = '英语',grade,0))English,
sum(grade)score
 from t_score
 
 -- 第三种
 select ifnull(name,'TOTAL')name,
sum(IF(subject = '语文',grade,0))Chiese,
sum(IF(subject = '数学',grade,0))Math,
sum(IF(subject = '英语',grade,0))English,
sum(grade)score
 from t_score GROUP BY name with rollup

结果

MySQL数据表列转行

 

相关文章:

  • 2022-12-23
  • 2021-12-25
  • 2021-11-19
  • 2021-05-01
  • 2022-12-23
  • 2021-08-09
猜你喜欢
  • 2021-10-24
  • 2021-06-03
  • 2021-12-22
  • 2022-02-19
  • 2022-12-23
  • 2022-12-23
  • 2022-01-05
相关资源
相似解决方案