MySQL Select 和 IF() 语句

MySQL Select and IF() Statement

我是 MySQL 的新手,我需要帮助。我有一个 table Invoices 和一个 table Payments。我无法生成一份报告,该报告将显示在 In Full 支付的所有发票或在 2019 年 12 月 31 日之前收到的 Partial Payment。一张发票可以通过一次或多次付款来支付(例如,部分付款,例如 25% 的定金,其余部分在工作完成时付款)。我如何创建 SQL 查询,该查询将 select 来自 Invoices 的所有记录,然后对于每个 select 匹配付款的发票,将其与 Invoice Total 进行比较并显示Paid in Full 还是 partial Payment?我有以下代码:

SELECT Invoices.InvoiceID, Invoices.ClientName, Invoices.InvoiceTotal
INNER JOIN InvoiceStatus ON InvoiceStatus.InvoiceStatusID = Invoices.InvoiceStatus
WHERE InvoiceDate BETWEEN '2019-1-1  00:00:00' AND '2019-12-31 23:59:59'
AND (Invoices.InvoiceStatus = '1' OR Invoices.InvoiceStatus = '2')
 AND (Invoices.InvoiceActive != 0 OR Invoices.InvoiceActive IS NULL)
ORDER BY ClientName

SELECT Payment.PaymentID, Payment.PaymentReceivedAmount, Payment.PaymentReceivedDate FROM `Payment` 
INNER JOIN Invoices ON Invoices.InvoiceID = Payment.InvoiceID
WHERE PaymentReceivedDate BETWEEN '2019-1-1  00:00:00' AND '2019-12-31 23:59:59'

如果我这样做 INNER JOIN 那么我会得到两行用于两次付款的发票。我知道我还需要实现 IF() 语句来显示 Paid in FullPartial Payment 但我有点迷路了。任何帮助将不胜感激!

您可以加​​入两个 table,按发票汇总,并使用 sum() 计算总付款。最后,可以用一个case表达式来显示状态:

select i.invoiceid, i.clientname, i.invoicetotal, 
    coalesce(sum(p.PaymentReceivedAmount), 0) as paymenttotal,
    case when i.invoicetotal <=> sum(p.PaymentReceivedAmount) then 'In Full' else 'Partial Payment' end as paymentstatus
from invoices i
left join payment p 
    on  p.invoiceid = i.invoiceid
    and p.paymentreceiveddate >= '2019-01-01' and p.paymentreceiveddate < '2020-01-01'
where 
    i.invoicedate >= '2019-01-01' and i.invoicedate < '2020-01-01'
    and i.invoicestatus in (1, 2)
    and (i.invoiceactive <> 0 or i.invoiceactive is null)
group by i.invoiceid
order by clientname

备注:

  • left join允许开具期间无任何付款的发票。

  • 我使用了与您原始查询中相同的日期过滤器,但通过将其变为半开间隔对其进行了一些优化。

  • 看来你不需要tableinvoicestatus来达到你想要的结果。