0

好的,我很抱歉问这个问题,因为我看到了几个 mysql JOIN 示例,但我似乎无法让它工作。

“销售量”

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

我想知道谁是最大的买家......就客户在特定日期从我这里购买东西的次数而言(是的,我使用一些奇怪的格式来表示我知道的日期,请不要介意)......所以我做:

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

问题是......因为我也有桌子:

“顾客”

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

以下是我想要实现的目标......如何做到这一点?

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

4 回答 4

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

于 2012-06-06T05:39:59.930 回答
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
于 2012-06-06T06:01:50.153 回答
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
于 2012-06-06T05:53:10.410 回答
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
于 2012-06-06T05:42:55.837 回答