码迷,mamicode.com
首页 > 数据库 > 详细

mysql 行转列,对列的分组求和,对行求和

时间:2019-04-30 23:44:07      阅读:425      评论:0      收藏:0      [点我收藏+]

标签:src   png   sel   mic   a+b   求和   info   行转列   end   

 

CREATE TABLE students(
  id INT PRIMARY KEY,
  NAME VARCHAR(11)
);

技术图片

CREATE TABLE courses(
  id INT PRIMARY KEY,
  NAME VARCHAR(11)
);

技术图片

 

CREATE TABLE scores(
  sid INT,
  cid INT,
  score INT,
  RIMARY KEY (sid,cid)
);

技术图片

 3表关联查询:

SELECT st.id,st.name,c.NAME course,sc.score FROM students st
LEFT JOIN scores sc ON st.id=sc.sid
LEFT JOIN courses c ON sc.cid=c.id

技术图片

将课程分类转为列名,其列值为分数:

SELECT t.id,t.name,
CASE course WHEN ‘语文‘ THEN score ELSE 0 END a,
CASE course WHEN ‘数学‘ THEN score ELSE 0 END b,
CASE course WHEN ‘英语‘ THEN score ELSE 0 END c,
CASE course WHEN ‘历史‘ THEN score ELSE 0 END d

FROM

(SELECT st.id,st.name,c.NAME course,sc.score FROM students st
LEFT JOIN scores sc ON st.id=sc.sid
LEFT JOIN courses c ON sc.cid=c.id) t

 技术图片

对上表按人员id分组,并将分完组的个列分数相加,组合到一行中,并对行求和:

SELECT t2.id,t2.name,SUM(a) ‘语文‘,SUM(b) ‘数学‘,SUM(c) ‘英语‘,SUM(d) ‘历史‘,SUM(a+b+c+d) ‘总分‘ FROM
(
  SELECT t.id,t.name,
  CASE course WHEN ‘语文‘ THEN score ELSE 0 END a,
  CASE course WHEN ‘数学‘ THEN score ELSE 0 END b,
  CASE course WHEN ‘英语‘ THEN score ELSE 0 END c,
  CASE course WHEN ‘历史‘ THEN score ELSE 0 END d

  FROM

    (SELECT st.id,st.name,c.NAME course,sc.score FROM students st
    LEFT JOIN scores sc ON st.id=sc.sid
    LEFT JOIN courses c ON sc.cid=c.id) t


) t2
GROUP BY t2.id;

 技术图片

 

mysql 行转列,对列的分组求和,对行求和

标签:src   png   sel   mic   a+b   求和   info   行转列   end   

原文地址:https://www.cnblogs.com/mryangbo/p/10798459.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!