SQL SUM question

后端 未结 5 1277

Hi I have a question about SUM in sql,

I have a query that looks like this

SELECT 
 SUM ( table_one.field + table_two.field )  as total_field
 SUM ( tota         


        
5条回答
  •  旧巷少年郎
    2021-01-28 11:39

    The name "total_field" is an alias and as such cannot be used in an aggregate functions The easiest and quickest way is to simply replace the code for total_field in the second calculation.

    SELECT
       SUM ( ISNULL(table_one.field,0) + ISNULL(table_two.field,0) )  as total_field
       SUM ( ISNULL(table_one.field,0) + ISNULL(table_two.field,0) +     IsNUll(table_one.anotherfield,0) )
    from
      table_one
    

    As your code doesn't cater for a null value in the fields you may get warnings when sum the values. I would suggest using IsNull as above and if there is a null value just treat it as 0.

提交回复
热议问题