从子查询计算的SQL查询

时间:2013-11-26 09:17:07

标签: mysql sql subquery

我有两张桌子(好吧,我有更多,但我简化了一些这个问题)

发票

invoiceID 10

invoiceNo 1234

invoiceAmount 1000

invoiceStatus 2

付款

paymentID 3

invoiceID 10

paymentAmount 500

paymentMethod 3

现在我需要一个查询,它从表Invoice中提供一些值,但也需要根据某个invoiceID的Payments值进行计算。我想得到的是:

Invoice number, invoice amount and remaining amount to pay
--------------  ---------------    -----------------------
1234            1000               500

你能帮助我用一个实际有效的子查询完成查询。

select i.invoiceNo as 'Invoice Number', i.invoiceAmount as 'Invoice amount' (i.invoiceAmount - totallyPayed) as reminingToPay
from Invoice i
left join Payments p on (p.invoiceID = i.invoiceID)
where 
i.invoiceStatus = 2 
and totallyPayed = (select sum(p.PaymentAmount) from Payments where p.paymentMethod in (1,2,3))

1 个答案:

答案 0 :(得分:1)

你可以这样做:

SELECT i.invoiceNo AS 'Invoice Number',
       i.invoiceAmount AS 'Invoice amount',
      (i.invoiceAmount - COALESCE(p.totalPayed,0)) AS remainingToPay
FROM Invoice i
LEFT JOIN (
  SELECT invoiceID,
         SUM(paymentAmount) AS totalPayed
  FROM payments
  WHERE paymentMethod IN (1, 2, 3)
  GROUP BY invoiceId
  ) p
  ON p.invoiceID = i.invoiceID
WHERE i.invoiceStatus = 2 

首先,您从每个invoiceID的付款表中获取paymentAmount的总和,然后加入您的发票表以获取剩余的付款。