SQL SUM question

后端 未结 5 1270

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.

    0 讨论(0)
  • 2021-01-28 11:41

    Try replacing "total_field" with "table_one.field + table_two.field" in second SUM().

    0 讨论(0)
  • 2021-01-28 11:45

    You cannot use the column alias in an aggregate to reference the value, just SUM again;

    SELECT 
     SUM ( table_one.field + table_two.field ) as total_field, --your missing a , also
     SUM ( table_one.field + table_two.field + table_one.anotherfield )
    FROM 
     table_one
    JOIN
     table_two ON table_one.id = table_two.id
    WHERE 
     table_one = 1
    
    0 讨论(0)
  • 2021-01-28 11:47

    SUM is an aggregate function. This means you can aggregate data from a field over several tuples and sum it up into a single tuple.

    What you want to do is this:

    SELECT 
      table_one.field + table_two.field,
      table_one.field + table_two.field + table_one.anotherfield
    

    or maybe this:

    SELECT 
      SUM(table_one.field) + SUM(table_two.field),
      SUM(table_one.field) + SUM(table_two.field) + SUM(table_one.anotherfield)
    
    0 讨论(0)
  • 2021-01-28 11:51

    You could use a subquery like this:

    SELECT
      total_field,
      total_field + sum_anotherfield
    FROM (
      SELECT 
        SUM(table_one.field + table_two.field) AS total_field,
        SUM(table_one.anotherfield) AS sum_anotherfield
      FROM 
        table_one
      JOIN
        table_two ON table_one.id = table_two.id
      WHERE 
        table_one.somefield = 1
    ) x
    
    0 讨论(0)
提交回复
热议问题