我真的在努力解决这个问题。我有4张桌子(http://oberto.co.nz/db-sql.png):
Invoice_Payement,Invoice,Client和Calendar。我试图通过按月/年总结Invoice_Payment中的'paid_amount'列来创建报告。
我尝试使用以下查询,但是当'paid_date'没有任何一个月的记录时,该查询就会失败。结果是月份未显示在结果中
我添加了一个Calendar表来解决这个问题但不确定如何保持联接。
SELECT
MONTHNAME(Invoice_Payments.date_paid) as month,
SUM(Invoice_Payments.paid_amount) AS total
FROM Invoice, Client, Invoice_Payments
WHERE Client.registered_id = 1
AND Client.id = Invoice.client_id
And Invoice.id = Invoice_Payments.invoice_id
AND date_paid IS NOT NULL
GROUP BY YEAR(Invoice_Payments.date_paid), MONTH(Invoice_Payments.date_paid)
请参阅上面的链接,了解我的方案的基本ERD图。
数据库:http://oberto.co.nz/ 预期输出:我下面的当前查询将返回如下内容:
month total
August 5
September 0
October 196
November 205
December 214
January 229
感谢阅读。 我以前发过这个问题,但我觉得我说的很糟糕。
答案 0 :(得分:0)
问题显然是你没有进行左连接,所以解决方案可能是重写查询以使用连接语法,您可以在其中指定您想要左连接。像
这样的东西在client.id = invoice.client_id left join
上从发票左侧加入客户端中选择*等等
答案 1 :(得分:0)
更新:P,这会有效吗?
SELECT YEAR(calendar.date_field) as year,
MONTHNAME(calendar.date_field) as month,
SUM(Invoice_Payments.paid_amount) AS total
FROM calendar
left outer join invoice_Payments on calendar.date_field = invoice_Payments.date_paid
left outer join Invoice on invoice_payments.invoice_id = invoice.invoice_id
left outer join (select * from client where registered_id = 1) as c on c.id = Invoice.client_id
GROUP BY YEAR(calendar.date_field), MONTH(calendar.date_field)
答案 2 :(得分:0)
这也可以起作用......
SELECT MONTHNAME(Invoice_Payments.date_paid) as month, SUM(Invoice_Payments.paid_amount) AS total
FROM Client
LEFT OUTER JOIN Invoice ON Client.id = Invoice.client_id
LEFT OUTER JOIN Invoice_Payments ON Invoice.id = Invoice_Payments.invoice_id
WHERE Client.registered_id = 1 AND date_paid IS NOT NULL
GROUP BY YEAR(Invoice_Payments.date_paid), MONTH(Invoice_Payments.date_paid);