如何获得多行的 table a 和 table b 的总和

How to get sum of table a and sum of table b with multiple rows

我有两个表:

表 1 作为

id date customer amount
1 2021-04-08 a 2
2 2021-04-08 a 3

表 2 作为 b

id orderid money
1 1 50
2 1 60
3 2 10
4 2 20

现在我想要日期、客户和表 1 中的金额总和以及表 2 中的金额总和。这意味着,结果应如下所示:

date customer amount money
2021-04-08 a 5 140

但是通过以下查询我得到了 10 的数量:

 select
      a.date,
      a.customer,
      sum(b.money) as money,       
      sum(a.amount) as amount
  from table1 a
    left join table2 b on a.id = b.orderid   
  group by date, customer

不知道怎么解决。

这很棘手。您需要聚合 before joining:

select a.date, a.num_customer, a.a_amount, b.b_amount
from (select a.date, count(*) as num_customer, sum(a.amount) as a_amount
      from table1 a
      group by a.date
     ) a left join
     (select a.date, sum(b.amount) as b_amount
      from table1 a join
           table2 b
           on a.id = b.orderid
      group by a.date
     ) b
     on a.date = b.date;

另一种方法是先通过orderid聚合第二个table,然后再次加入并聚合:

select a.date, count(*) as num_customer, sum(a.amount),
       sum(b.b_amount)
from table1 a left join
     (select b.orderid, sum(b.amount) as b_amount
      from table2 b
      group by b.orderid
     ) b
     on a.id = b.orderid
group by a.date