好的伙计们,我很遗憾地问这个,因为我看过几个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
答案 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
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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