Reputation: 97
my sql is a bit rusty (not really that great to begin with!)
I'm trying to write a query that searches through a single table, now within this table there are numerous customers buying some item. Now obviously I can search by the customer, as in
select * from purchases where customer_name "Brian" and product_name like 'Al%;
My problem is what I'm wanting to do is, in a query like that, I want to list all the customer names that have purchased like 'Al%' and the count.
So "Alcohol", etc, would only ever be once per record in the data. But say "Brian" purchases alcohol, all day breakfast, alcohol (all in separate records). I would want to count those, so my return would be "Brian 3".
My final failed attempt was below (not sure it will help!)
select purchases.customer_name, COUNT(purchases.product_name like 'Al%') As Al purchases from purchases;
Thanks in advance. It may be something very simple and I'm totally messing it up in my head!
Upvotes: 0
Views: 280
Reputation: 56
You forgot to add GROUP BY
select purchases.customer_name, purchases.product_name, COUNT(purchases.product_name) from purchases where customer_name "Brian" and product_name like 'Al% GROUP BY purchases.product_name, purchases.customer_name;
You will get
Brian, Alcohol, 2
Brian, Alcohol Jin, 3
Upvotes: 3
Reputation: 1148
Write This Way::
That Can Solve Your Problem.
select purchases.customer_name, COUNT(purchases.product_name) As Al from purchases where purchases.product_name like 'Al%' Group by purchases.product_name;
Upvotes: 0