How to SUM two fields within an SQL query

前端 未结 8 2042
南笙
南笙 2020-11-28 21:58

I need to get the total of two fields which are within the same row and input that number in a field at the end of that same row.

This is my code.

S         


        
8条回答
  •  隐瞒了意图╮
    2020-11-28 22:34

    SUM is an aggregate function. It will calculate the total for each group. + is used for calculating two or more columns in a row.

    Consider this example,

    ID  VALUE1  VALUE2
    ===================
    1   1       2
    1   2       2
    2   3       4
    2   4       5
    

     

    SELECT  ID, SUM(VALUE1), SUM(VALUE2)
    FROM    tableName
    GROUP   BY ID
    

    will result

    ID, SUM(VALUE1), SUM(VALUE2)
    1   3           4
    2   7           9
    

     

    SELECT  ID, VALUE1 + VALUE2
    FROM    TableName
    

    will result

    ID, VALUE1 + VALUE2
    1   3
    1   4
    2   7
    2   9
    

     

    SELECT  ID, SUM(VALUE1 + VALUE2)
    FROM    tableName
    GROUP   BY ID
    

    will result

    ID, SUM(VALUE1 + VALUE2)
    1   7
    2   16
    

提交回复
热议问题