SELECT w.title, c.CustomerID, COUNT(o.form_id) as cnt
FROM warehouse w
JOIN customer c USING (countrycode)
JOIN `Order` o USING (CustomerID)
GROUP BY w.siteid, c.CustomerID
ORDER BY w.title ASC, c.CustomerID
編輯
如果要包括客戶沒有任何訂單,則需要一個LEFT JOIN Customers表:
SELECT w.title, c.CustomerID, COUNT(o.form_id) as cnt
FROM warehouse w
JOIN customer c USING (countrycode)
LEFT JOIN `Order` o USING (CustomerID)
GROUP BY w.countrycode, c.CustomerID
ORDER BY w.title ASC, c.CustomerID
若要篩選,只有一個客戶:
SELECT w.title, c.CustomerID, COUNT(o.form_id) as cnt
FROM warehouse w
JOIN customer c USING (countrycode)
LEFT JOIN `Order` o USING (CustomerID)
WHERE c.CustomerId = 2
GROUP BY w.countrycode, c.CustomerID
ORDER BY w.title ASC, c.CustomerID
您可能想要提供一些示例數據和所需的結果,而不是鏈接到沒有人可以測試或驗證結果是否正確的圖像。 http://sqlfiddle.com/非常適合設置測試,但樣本數據和期望的結果應該成爲未來訪問者有類似問題的參考。 –