0

mysql我的脚本有问题。

我有 2 张桌子,我想在另一张桌子上比较我invoiceAmount的。paymentAmount情况是:一张发票可以有很多付款,我想invoiceAmount (table A)paymentAmount (table B).

我已经用paymentAmount相同的 invoiceID 计算加入了它,我的问题是如何比较它(所有行的两个表中相同 invoiceID 的总和)paymentAmount(table B)invoiceAmount (table A)真的需要你们的帮助。。

我的脚本是:

SELECT invoice.InvoiceID, invoice.InvoiceAmount, pays.InvoiceID, sum(pays.PaymentAmount) as pays, invoice.InvoiceDate 
FROM `payment from customer` as pays
JOIN invoice ON(pays.InvoiceID=invoice.InvoiceID)
WHERE pays.InvoiceID in (
    SELECT InvoiceID 
    FROM `payment from customer`
    GROUP BY InvoiceID
    HAVING count(*) > 1)
GROUP BY pays.InvoiceID
4

2 回答 2

0
SELECT * 
FROM (select invoice.InvoiceID, 
             invoice.InvoiceAmount, 
             pays.InvoiceID, 
             pays.PaymentAmount as pays, 
             invoice.InvoiceDate ,
             (select sum(a.PaymentAmount) 
                from `payment from customer` a 
               where a.InvoiceID = invoice.InvoiceID) totalPays
        from `payment from customer` as pays JOIN invoice 
          ON (pays.InvoiceID=invoice.InvoiceID) ) temp
where InvoiceDate > totalPays
于 2013-07-08T08:40:15.347 回答
0

在结果表中添加一个字段,您可以在其中计算仍需支付的总和。

例如,如果您想要一个仍有余额要支付的发票列表:

  SELECT invoice.InvoiceID,
         invoice.InvoiceAmount,
         pays.InvoiceID,
         sum(pays.PaymentAmount) AS pays,
         sum(pays.PaymentAmount) - invoice.InvoiceAmount AS StillToPay
         invoice.InvoiceDate
    FROM `payment from customer` AS pays
         JOIN invoice ON pays.InvoiceID = invoice.InvoiceID
   WHERE pays.InvoiceID IN (   SELECT InvoiceID FROM `payment from customer`
                             GROUP BY InvoiceID
                               HAVING count(*) > 1 )
     AND StillToPay > 0
GROUP BY pays.InvoiceID

未经测试的查询!

于 2013-07-08T08:40:53.693 回答