表A:qa_invoices
invoice_code invoice_date
1 25
2 25
3 26
4 27
表B:qa_invoicesitems
invoice_code item_quantity item_name
1 2 Mouse
1 1 CPU
2 5 Keyboard
3 1 Router
4 3 Switch
我的查询:
SELECT SUM(qa_invoicesitems.item_quantity) AS item_count, COUNT(*) AS invoice_count
FROM qa_invoices
LEFT OUTER JOIN qa_invoicesitems USING (invoice_code)
WHERE qa_invoices.invoice_date = 25
我的结果:
item_count invoice_count
8 3
我有时间和时间寻找解决方案,问题是计算发票(invoice_count)。
正确的结果是:
item_count invoice_count
8 2
如果有人可以帮助我解决我的问题。
答案 0 :(得分:1)
尝试将DISTINCT添加到您的COUNT。
SELECT SUM(qa_invoicesitems.item_quantity) AS item_count, COUNT(DISTINCT(qa_invoicesitems.invoice_code)) AS invoice_count
FROM qa_invoices
LEFT OUTER JOIN qa_invoicesitems USING (invoice_code)
WHERE qa_invoices.invoice_date = 25