【问题标题】:Average between columns in mysqlmysql中列之间的平均值
【发布时间】:2013-11-01 14:17:07
【问题描述】:

我需要计算学生获得的 3 个成绩的平均成绩。

ID      subject     G1  G2  G3
12345   Math        90  80  77
12345   Physics     99  89  78
12345   Network     76  60  90
99999   Math        50  90  88
99999   Chemistry   80  70  88
88888   English     90  90  100
88888   Physics     90  89  79

这些是 MySQL 数据库中的条目,我需要一种方法来计算 3 列之间每行的这些条目的平均值

所以当输出在网络上检索时,它看起来像这样

subject     gradeone    gradetwo    gradethree  average
Math        90          80          77  

感谢任何帮助!非常感谢!

【问题讨论】:

  • protip:看AVG函数。
  • @BradChristie 看起来.. 不太管用
  • 你总是可以(g1+g2+g3)/3
  • @BradChristie AVG 仅适用于列平均值
  • @SavTheCoder:我很抱歉,但我假设没有 3 个固定的 Gn 列。

标签: php html mysql mysqli


【解决方案1】:

Example

SELECT subject,
       g1 as gradeone,
       g2 as gradetwo,
       g3 as gradethree,
       (g1+g2+g3)/3 as average
FROM   students

结果:

SUBJECT     GRADEONE  GRADETWO  GRADETHREE  AVERAGE
Math        90        80        77          82.3333
Physics     99        89        78          88.6667
Network     76        60        90          75.3333
Math        50        90        88          76
Chemistry   80        70        88          79.3333
English     90        90        100         93.3333
Physics     90        89        79          86

【讨论】:

  • @Brad - 我只是好奇为什么标题都是大写的。
  • @Fred-ii-: SqlFiddle 本身就是这样做的——不知道为什么。
  • @BradChristie 这就是我的想法,我将编辑我的评论,说明它是否是它所在服务器的专有;谢谢你。顺便说一句,为您的答案 +1,这样的答案/问题可以证明是非常有用的,干杯。
  • @TimValishin:如果您想要一种更好的方式来组织信息,而不是只关注三个等级:sqlfiddle.com/#!2/ee3caf/2/0
【解决方案2】:
SELECT subject,
       G1 AS gradeone,
       G2 AS gradetwo,
       G3 AS gradethree,
       ((G1 + G2 + G3) / 3) AS average
FROM   tablename;

假设您的考试成绩从不超过三个,这将为您提供您想要的每个学生的输出。

【讨论】:

    【解决方案3】:

    你可以像使用sql-

    select subject, 
           g1 as gradeone, 
           g2 as gradetwo, 
           g3 as gradethree, 
           ((g1+g2+g3)/3) as average 
    from tablename where id=12345;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-14
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多