Getting the sum of several columns from two tables

前端 未结 5 520
生来不讨喜
生来不讨喜 2021-01-11 16:26

I want to get the sum of several columns from 2 different tables (these tables share the same structure).

If I only consider one table, I would write this kind of qu

5条回答
  •  长情又很酷
    2021-01-11 17:24

    You can union your tables before the group by (this is on Oracle, by the way):

    SELECT t.month_ref, SUM(t.amount1), SUM(t.amount2)
      FROM (SELECT month_ref, amount1, amount2
              FROM T_FOO
             WHERE seller = XXX
             UNION ALL
            SELECT month_ref, amount1, amount2
              FROM T_BAR
             WHERE seller = XXX
             ) t
     GROUP BY t.month_ref
    

    You may also union the tables with the seller field and filter by it later (in case you need more advanced logic):

     SELECT t.month_ref, SUM(t.amount1), SUM(t.amount2)
       FROM (SELECT month_ref, amount1, amount2, seller
               FROM T_FOO
              UNION ALL
             SELECT month_ref, amount1, amount2, seller
               FROM T_BAR) t
      where t.seller = XXX
      GROUP BY t.month_ref
    

提交回复
热议问题