0

Ok folks, im sorry to ask about this since ive seen a couple of mysql JOIN examples but i seem to be unable to get it to work.

"sales"

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

I want to know who is the top buyer.... in terms of HOW MANY TIMES a customer buys something from me on a especific day (yes i use some weird format for date i know, please nevermind that)...so i do:

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

AND I GET:

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

Question is... since i also have the table:

"customer"

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

And below is what i would like to achieve.... how to do so?

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

4 Answers 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

See it working online: sqlfiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the replay. Loved the sqlfiddle.
0

You will need to do it this way -

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

Comments

0

Hope this will help ::

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

Comments

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

1 Comment

This method i have not seen before. I shall investigate further into it. ty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.