将差值与差值表中相同ID的其他值进行比较

时间:2013-07-08 08:01:57

标签: mysql sql

我的mysql脚本存在问题。

我有2个表,我想在另一个表中将invoiceAmountpaymentAmount进行比较。情况是:许多付款可以用于一张发票,我想将invoiceAmount (table A)paymentAmount (table B)进行比较。

我已经使用相同invoiceID的计算paymentAmount加入了它,我的问题是如何比较它(所有行的两个表中相同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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

未经测试的查询!