SQL 2 Summations发出错误的结果

时间:2014-10-28 08:54:19

标签: mysql sql database

我在做一个查询,在那里我做了2次求和,但它给出了一个奇怪的结果

SELECT
    SUM(Details.price * Details.quantity) AS total_amount,
    SUM(Payment.amount_paid) as paid_amount
FROM
    Details,
    Invoice
LEFT JOIN
    Payment ON Invoice.id = Payment.fk_invoice_id
WHERE
    AND Invoice.id = 1
    AND Invoice.id = Details.fk_invoice_id
GROUP BY Details.fk_invoice_id;

当前正在发生的事情是,假设在Payment中有3行与选择条件匹配,在详细信息上只有1行,total_amount中的总和乘以3但paid_amount是正确的。然后让我们说明细节中有2个项目符合条件,而付款只有1,paid_amount乘以2但total_amount是正确的。任何提示都会很棒,谢谢!

模式

Invoice
    id
    Name....


Details
    id
    fk_invoice_id
    name
    price
    quantity

Payment
    id
    fk_invoice_id
    amount_paid

更多详情:

我试图简化我的帖子,但只是添加

客户有很多发票

我只有对客户的引用,所以customer.id是发票中的外键,我试图获取特定客户的所有发票。

1 个答案:

答案 0 :(得分:1)

您要做的就是从每张发票上的详细信息和付款中总结一些东西。但是你加入了所有相关记录。所以说发票有3条详细记录和2条付款记录,然后您将详细结果乘以2,将付款结果乘以3.您可以划分:

SELECT
  SUM(Details.price * Details.quantity) / GREATEST(COUNT(DISTINCT Payment.id),1) AS total_amount,
  SUM(Payment.amount_paid) / COUNT(DISTINCT Details.id) as paid_amount
FROM Details
JOIN Invoice ON Invoice.id = Details.fk_invoice_id AND Invoice.id = 1
LEFT JOIN Payment ON Invoice.id = Payment.fk_invoice_id
GROUP BY Invoice.id;

或者根本不加入不得加入的内容。这是一种方式:

SELECT
  (SELECT SUM(Details.price * Details.quantity) FROM Details WHERE Details.fk_invoice_id = Invoice.id) AS total_amount,
  (SELECT SUM(Payment.amount_paid) FROM Payment WHERE Payment.fk_invoice_id = Invoice.id) AS paid_amount
FROM Invoice 
WHERE id = 1;

这是另一个,在聚合之前完成聚合。 (顺便说一下,我们不需要发票表。我在这里删除它。)

SELECT
  d.total_amount,
  p.paid_amount
FROM 
(
  SELECT fk_invoice_id, SUM(price * quantity) as total_amount
  FROM Details 
  GROUP BY fk_invoice_id
) d ON d.fk_invoice_id = Invoice.id
LEFT JOIN 
(
  SELECT fk_invoice_id, SUM(Payment.amount_paid) as paid_amount
  FROM Payment 
  GROUP BY fk_invoice_id
) p ON p.fk_invoice_id = Invoice.id
WHERE d.fk_invoice_id = 1;

只要您只是寻找一个发票ID,所有上述陈述当然都可以简化。例如:

SELECT
  (SELECT SUM(Details.price * Details.quantity) FROM Details WHERE Details.fk_invoice_id = 1) AS total_amount,
  (SELECT SUM(Payment.amount_paid) FROM Payment WHERE Payment.fk_invoice_id = 1) AS paid_amount;