2012-06-06 107 views
0

好的夥計們,很抱歉,因爲我看到了一些mysql JOIN示例,但我似乎無法讓它工作。mysql + JOIN查詢的問題

「銷售」

---------------------- 
idcustomer | datecode 
---------------------- 
1   | 20120503 
1   | 20120503 
1   | 20120503 
2   | 20120503 
3   | 20120503 

我想知道誰是最大買家....在多少次客戶從我這裏買走的東西在especific天方面(是的,我用一些奇怪的格式日期我知道,請不要介意說)......,所以我做的:

SELECT idcustomer, COUNT(idcustomer) FROM sales WHERE datecode = 20120503 GROUP BY idcustomer ORDER BY COUNT(idcustomer) DESC 

,我也得到:

----------------------------- 
idcustomer | Count(idcustomer) 
----------------------------- 
1   | 3 
2   | 1 
3   | 1 

的問題是... SI NCE我也有表:

「客戶」

---------------------- 
| name | id_customer | 
---------------------- 
Jess | 1 
Matt | 2 
Perry | 3 

及以下就是我想達到什麼樣的....怎麼辦呢?

--------------------------------------------- 
customer.name | idcustomer | Count(idcustomer) 
--------------------------------------------- 
Jess   | 1   | 3 
Matt   | 2   | 1 
Perry  | 3   | 1 
+0

按日期代碼添加分組 –

回答

1
SELECT customer.name, idcustomer, COUNT(idcustomer) 
FROM sales 
JOIN customer 
ON sales.idcustomer = customer.id_customer 
WHERE datecode = 20120503 
GROUP BY idcustomer 
ORDER BY COUNT(idcustomer) DESC 

看到它聯機工作:sqlfiddle

+0

感謝您的重播。喜歡sqlfiddle。 – Khul

0

你需要做這種方式 -

SELECT idcustomer, c.name, COUNT(idcustomer) 
FROM sales s inner join customer c on (s.idcoustomer=c.id_customer) 
WHERE datecode = 20120503 
GROUP BY idcustomer, c.name 
ORDER BY COUNT(idcustomer) DESC 
+0

感謝您的回覆! – Khul

0

希望這將有助於::

Select cust_ref.idcustomer, cust_ref.COUNT(idcustomer), customer.name 
from 
(SELECT idcustomer, COUNT(idcustomer) FROM sales WHERE datecode = 20120503 
GROUP BY idcustomer) cust_ref 
inner join customer on (sales.idcustomer = customer.id_customer) 
ORDER BY COUNT(idcustomer) DESC 
0
SELECT 
    t1.name,t2.count_buy,t2.idcustomer 
    FROM customer as t1, 
(SELECT 
    idcustomer,COUNT(idcustomer) as count_buy 
     FROM `sales` 
     WHERE datecode = 20120503 
     GROUP BY idcustomer 
     ORDER BY COUNT(idcustomer) DESC) t2 
    WHERE 
    t1.idcustomer =t2.idcustomer 
+0

這種方法我以前沒有見過。我將進一步調查。 TY – Khul