How to add column values in mysql

前端 未结 7 1996
醉话见心
醉话见心 2020-12-09 15:37

This is my table data Student

\"enter

And this is my query --

相关标签:
7条回答
  • 2020-12-09 16:07

    Sum is a aggregate function. You dont need to use it. This is the simple query -

    select *,(maths + chemistry + physics ) AS total FROM `student`
    
    0 讨论(0)
  • 2020-12-09 16:08

    Try this

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

    You are done. Thanks

    0 讨论(0)
  • 2020-12-09 16:13

    You don't need use SUM for this operation. Try this query:

    SELECT id, ( maths + chemistry + physics ) AS total, maths, chemistry, physics
    FROM `student`
    
    0 讨论(0)
  • 2020-12-09 16:18

    The sum function in MySQL works in the sense that it gives you the sum of values in a column from your select statement. If you need to sum values from a row in your query, then just use plus (+) What you need is this query :

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

    This will give you the results you need.

    0 讨论(0)
  • 2020-12-09 16:19

    If you're requiring to get total marks of each student, then SUM is not what you'd be needing.

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

    Will do the job just fine.

    0 讨论(0)
  • 2020-12-09 16:28

    Tip: If one of the fields has the possibility to be NULL, then use COALESCE to default these to 0, otherwise total will result in NULL.

    SELECT *, (
        COALESCE(maths, 0) +
        COALESCE(chemistry, 0) +
        COALESCE(physics, 0)
    ) AS total 
    FROM `student`
    
    0 讨论(0)
提交回复
热议问题