试试这个:http ://www.sqlfiddle.com/#!2/d8d9c/9
这里是总结的变化
- 我摆脱了你的
GROUP BY
. 您没有任何聚合函数。我用来DISTINCT
消除重复记录
- 我删除了您的隐式连接并将显式连接放在它们的位置以提高可读性。然后我将它们更改为 LEFT JOIN。我不确定您的数据是什么样的,但至少,如果您想选择没有付款的发票,我会假设您需要付款 LEFT JOINed。
- 这可能会为您提供所需的记录,但是
SELECT
子句中的那些子选择作为 LEFT JOIN 可能比使用 SUM 函数执行得更好
这是查询
SELECT DISTINCT
a.abbr landowner,
CONCAT(f.ForestLabel, '-', l.serial, '-', l.revision) leasenumber,
i.iid,
FROM_UNIXTIME(i.dateadded,'%M %d, %Y') InvoiceDate,
(SELECT IFNULL(SUM(ch.amount), 0.00) n FROM test_charges ch WHERE ch.invoiceid = i.iid) totalBilled,
(SELECT SUM(p1.amount) n FROM test_payments p1 WHERE p1.invoiceid = i.iid AND p1.transtype = 'check' AND p1.status = 2) checks,
(SELECT SUM(p1.amount) n FROM test_payments p1 WHERE p1.invoiceid = i.iid AND p1.transtype = 'ach' AND p1.status = 2) ach,
CASE WHEN i.totalbilled < 0 THEN i.totalbilled * -1 ELSE 0.00 END credits,
CASE WHEN i.balance >= 0 THEN i.balance ELSE 0.00 END balance,
t.typelabel, g.groupname
FROM test_invoices i
LEFT JOIN test_contracts c
ON i.contractid = c.cid
LEFT JOIN test_leases l
ON c.leaseid = l.bid
LEFT JOIN test_forest f
ON l.forest = f.ForestID
LEFT JOIN test_leasetypes t
ON l.leasetype = t.tid
LEFT JOIN test_accounts a
ON l.account = a.aid
LEFT JOIN test_groups g
ON c.groupid = g.gid
LEFT JOIN test_payments p
ON p.invoiceid = i.iid
WHERE (i.dateadded >= @startdate) OR (p.dateadded >= @startdate)