使用 2 个内部联接时,第二个 table 上的列总和不正确

incorrect sum of columns on second table when using 2 inner joins

我有 3 个 sqlite tables 客户、销售和发票。我在 invoice.amount 上得到的总和在下面的查询中不正确,sum.amount 打折 table 是正确的。

我的查询是

SELECT  sum(invoice.amount)  as 'amt' 
       , customer.name
       , sum(sale.amount) as 'amt1' 
FROM    customer 
          INNER JOIN sale on customer.customer_id  = sale.customer_id 
          INNER JOIN invoice on customer.customer_id = invoice.customer_id
WHERE  (
         (sale.date <='2022-04-30') and 
         (invoice.date <='2022-04-30') and 
         customer.area='xyz' and 
         ( 
             customer.status='Active' OR 
             customer.status='Inactive'
         ) 
) 
GROUP BY customer.customer_id 
ORDER BY customer.delseq ASC

如果我只使用如下所示的一个内部联接并跳过销售 table,那么我会得到正确的结果。

SELECT  sum(invoice.amount)  as 'amt' 
       , customer.name 
FROM   customer 
           INNER JOIN invoice ON customer.customer_id = invoice.customer_id
WHERE  (
          ( invoice.date <='2022-04-30') and 
            customer.area='xyz' and 
            ( 
               customer.status='Active' 
               OR 
               customer.status='Inactive'
            ) 
) 
GROUP BY customer.customer_id 
ORDER BY customer.delseq ASC

您必须在每个 table 中单独汇总,然后加入,如果存在客户没有销售或发票的情况,则可以使用 LEFT 而不是 INNER 加入给定的日期范围:

SELECT c.name, i.amt, s.amt1
FROM customer c
LEFT JOIN (
  SELECT customer_id, SUM(amount) amt1
  FROM sale 
  WHERE date <='2022-04-30'
  GROUP BY customer_id
) s ON c.customer_id  = s.customer_id 
LEFT JOIN (
  SELECT customer_id, SUM(amount) amt 
  FROM invoice 
  WHERE date <='2022-04-30'
  GROUP BY customer_id
) i ON c.customer_id  = i.customer_id 
WHERE c.status='Active' OR c.status='Inactive'
ORDER BY c.delseq ASC;