a simple way to sum a result from UNION in MySql

前端 未结 5 1219
北海茫月
北海茫月 2020-12-24 06:03

I have a union of three tables (t1,t2,t3). Each rerun exactly the same number of records, first column is id, second amount:

1  10
2  20
3  20

1  30
2  3         


        
相关标签:
5条回答
  • 2020-12-24 06:29

    Subquery:

    SELECT id, SUM(amount)
    FROM ( SELECT * FROM t1
           UNION ALL SELECT * FROM t2
           UNION ALL SELECT * FROM t3
         )
    GROUP BY id
    
    0 讨论(0)
  • 2020-12-24 06:32
    SELECT id, SUM(amount) FROM
    (
        SELECT id, SUM(amount) AS `amount` FROM t1 GROUP BY id
      UNION ALL
        SELECT id, SUM(amount) AS `amount` FROM t2 GROUP BY id
    ) `x`
    GROUP BY `id`
    

    I groupped each table and unioned because i think it might be faster, but you should try both solutions.

    0 讨论(0)
  • 2020-12-24 06:36

    Yes!!! Its okay! Thanks!!!! My code finishing:

    SELECT SUM(total) 
    FROM ( 
            (SELECT 1 as id, SUM(e.valor) AS total  FROM entrada AS e)
        UNION 
            (SELECT 1 as id, SUM(d.valor) AS total FROM despesa AS d)
        UNION 
            (SELECT 1 as id, SUM(r.valor) AS total FROM recibo AS r WHERE r.status = 'Pago')
    )  x group by id
    
    0 讨论(0)
  • 2020-12-24 06:40

    Not sure if MySQL uses common table expression but I would do this in postgres:

    WITH total AS(
                  SELECT id,amount AS amount FROM table_1 UNION ALL
                  SELECT id,amount AS amount FROM table_2 UNION ALL
                  SELECT id,amount AS amount FROM table_3
                 )
    SELECT id, sum(amount)
      FROM total
    

    I think that should do the trick as well.

    0 讨论(0)
  • 2020-12-24 06:52
    select id, sum(amount) from (
        select id,amount from table_1 union all
        select id,amount from table_2 union all
        select id,amount from table_3
    ) x group by id
    
    0 讨论(0)
提交回复
热议问题