2012-01-10 163 views
1

我有命名爲出納,SALES三個不同的表,和REFUNDS計算兩個不同的列的總和的兩個表

CASHIER表具有:

cashierID/cashier_name

SALES表具有:

salesID/cashierID/amountReceived

REFUNDS表具有:

refundsID/cashierID/amountRefunded

我想顯示經由amountReceived從銷售和退款接收的收銀員的總量和分別amountRefunded列。會有一個MySQL的語法嗎?非常感謝!

回答

1
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 
+0

我認爲這就是它!非常感謝。 但我可以問一個問題,什麼是COALESCE(字段1,0)的含義? – mathan0690 2012-01-10 03:11:57

+0

如果出納員沒有出售或沒有返回任何東西,您將從LEFT JOIN獲得0而不是NULL。 – piotrm 2012-01-10 03:14:10

+0

好的。再次感謝! – mathan0690 2012-01-10 03:16:43

1
select 
    c.cashierID, 
    c.cashier_name, 
    sum(s.amountReceived) as totalReceived, 
    sum(r.amountRefunded) as totalRefunded 
from CASHIER c 
left join SALES s on s.cashierID = c.cashierID 
left join REFUNDS r on r.cashierID = c.cashierID 
group by 1,2 
+1

+1。以略勝一籌的速度擊敗我。 (有趣的是,它甚至包括了與表格相同的別名選擇。):) – 2012-01-10 02:25:08

+0

先生,你會介意我問這個問題嗎?在你的小組中,1和2,你是什麼意思?你是否將它與第一列和第二列分組? – 2012-01-10 02:30:48

+1

@johntotetwoo GROUP BY 1,2''是SQL標準縮寫,意思是「GROUP BY ,」,即在這種情況下具有與「GROUP BY c.cashierID,c.cashier_name」完全相同的含義。許多人不喜歡這樣,但我發現它遠遠更容易閱讀和維護。順便說一句,你可以列出儘可能多的列號,只要你喜歡什麼順序 – Bohemian 2012-01-10 02:48:20