【问题标题】:How to add column values in mysql如何在mysql中添加列值
【发布时间】:2012-09-05 09:46:59
【问题描述】:

这是我的表格数据Student

这是我的查询--

SELECT id, SUM( maths + chemistry + physics ) AS total, maths, chemistry, physics
FROM `student`

但它只抛出一行 --

id  total   maths   chemistry   physics
118     760     55  67  55

虽然我想对所有 id 应用 sum ....让我知道如何实现这一点?

【问题讨论】:

    标签: mysql sql logic sum


    【解决方案1】:

    Sum 是一个聚合函数。你不需要使用它。这是简单的查询 -

    select *,(maths + chemistry + physics ) AS total FROM `student`
    

    【讨论】:

      【解决方案2】:

      提示:如果其中一个字段可能为 NULL,则使用 COALESCE 将这些字段默认为 0,否则 total 将导致 NULL。

      SELECT *, (
          COALESCE(maths, 0) +
          COALESCE(chemistry, 0) +
          COALESCE(physics, 0)
      ) AS total 
      FROM `student`
      

      【讨论】:

      • 如果您要添加很多列,还有比这更简单的方法吗?也许是数据库设置?
      【解决方案3】:

      如果您需要获得每个学生的总分,那么SUM 不是您需要的。

      SELECT id,
          (maths+chemistry+physics) AS total,
          maths,
          chemistry,
          physics
      FROM `student`
      

      会很好地完成这项工作。

      【讨论】:

      • 另一个有趣的答案..你们太棒了..对学习者来说非常有用的平台:)
      【解决方案4】:

      此操作不需要使用SUM。试试这个查询:

      SELECT id, ( maths + chemistry + physics ) AS total, maths, chemistry, physics
      FROM `student`
      

      【讨论】:

        【解决方案5】:

        MySQL 中的 sum 函数的工作原理是它为您提供 select 语句中某一列中值的总和。如果您需要对查询中一行的值求和,则只需使用 plus (+) 您需要的是这个查询:

        SELECT id, (`maths` +`chemistry`+`physics`) AS `total`, `maths`, `chemistry`, `physics`
        FROM `student`;
        

        这将为您提供所需的结果。

        【讨论】:

        • FROM 前的反引号是错字吧?
        【解决方案6】:

        所有聚合函数都适用于由 rowname 和 group by 操作指定的行。您需要对单个行进行操作,这不是任何聚合函数的选项。

        【讨论】:

          【解决方案7】:

          试试这个

          SELECT id, ( maths + chemistry + physics ) AS total, maths, chemistry, physics
          FROM `student`
          

          你已经完成了。谢谢

          【讨论】:

            猜你喜欢
            • 2016-05-25
            • 1970-01-01
            • 1970-01-01
            • 2023-03-18
            • 2018-07-19
            • 2023-01-05
            • 1970-01-01
            • 2022-11-03
            • 1970-01-01
            相关资源
            最近更新 更多