SELECT c.cashier_name AS cashier,
COALESCE(salesByCashier.totalSales, 0) AS sales,
COALESCE(refundsByCashier.totalRefunded, 0) AS refunds,
COALESCE(salesByCashier.totalSales, 0) -
COALESCE(refundsByCashier.totalRefunded, 0 ) AS total
FROM
cashier c
LEFT JOIN
(SELECT s.cashierID AS cashierID, SUM(amountReceived) AS totalSales
FROM sales s
GROUP BY s.cashierID) salesByCashier
ON c.cashierID = salesByCashier.cashierID
LEFT JOIN
(SELECT r.cashierID AS cashierID, SUM(amountRefunded) AS totalRefunded
FROM refunds r
GROUP BY r.cashierID) refundsByCashier
ON c.cashierID = refundsByCashier.cashierID
我認爲這就是它!非常感謝。 但我可以問一個問題,什麼是COALESCE(字段1,0)的含義? – mathan0690 2012-01-10 03:11:57
如果出納員沒有出售或沒有返回任何東西,您將從LEFT JOIN獲得0而不是NULL。 – piotrm 2012-01-10 03:14:10
好的。再次感謝! – mathan0690 2012-01-10 03:16:43