【问题标题】:MySQL Select and IF() StatementMySQL Select 和 IF() 语句
【发布时间】:2021-03-13 19:14:27
【问题描述】:

我是 MySQL 的新手,我需要帮助。我有一张桌子Invoices 和一张桌子Payments。我无法生成一份报告,该报告将显示以 In Full 支付的所有发票,或在 2019 年 12 月 31 日之前收到 Partial Payment 的所有发票。一张发票可以通过一笔或多笔付款来支付(例如,部分付款,例如 25% 的首付,其余部分在工作完成时付款)。如何创建 SQL 查询,从 Invoices 中选择所有记录,然后为每个 Invoice 选择匹配的 Payment,将其与 Invoice Total 进行比较并显示 Paid in Fullpartial 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 但我有点迷茫。任何帮助将不胜感激!

【问题讨论】:

  • 您的查询错过了 FROM,肯定不会运行。另外描述与代码不匹配,请改进。

标签: mysql sql sum left-join aggregate-functions


【解决方案1】:

您可以连接两个表,按发票汇总,并使用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 允许在此期间无需任何付款的发票。

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

  • 您似乎不需要表invoicestatus 来获得您想要的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-25
    • 2016-07-20
    • 2016-12-29
    • 2014-02-15
    • 2012-10-11
    • 2015-10-22
    • 1970-01-01
    • 2013-09-21
    相关资源
    最近更新 更多