how to count number of customer referrals? - mysql

I have a table that looks like the following:
Cust_ID . Cust_name . Cust_referred_by
1 Allan 2
2 Blake 3
3 Jen 2
4 Zeke 1
In this scenario Allan was referred by Blake. How do I count how many referrals each customer has?
so far I have this code:
select cust_name, count(cust_referred_by)
from Customer
I believe I have to use self join table but not sure how to implement

Assuming you want to count the cust_reffered_by for each customer, then you can use the following query:
select cust_name, count(cust_reffered_by)
from Customer
group by cust_name
What I think you want to do, is to count the number of times a customer has been referred to. You can achieve that with the following query:
select cust_name, count(cust_id)
from Customer
group by cust_name
Without more information about the semantics of the table, it's hard to be sure what you're looking for though.

You can use group by and join to do it
select a.cust_name, count(b.Cust_ID)
from Customer a
join Customer b on a.Cust_ID=b.Cust_referred_by
group by a.cust_name

You can use this query to get sum of one column values:
$result=mysql_query("SELECT SUM(Cust_referred_by) AS total FROM Customer");
$row = mysql_fetch_array($result);
$sum = $row['total'];
echo $sum;

select
t.Cust_ID,
t.Cust_name,
(select count(s.Cust_ID) from Customer as s where s.Cust_referred_by = t.Cust_ID) as Referred
from Customer as t
You should use sub query for better versatility.
Using Group by is a very bad design, since you cannot group by two column at the same time.

Related

MySQL get count from two related tables

I am using MySQL and database server and I have two tables one is for customer and another for customer_contacts.
Here are the table structures:
customer(
id(pk, ai)
name
email
)
and
customer_contacts(
id(ai)
customer_id
first_name
last_name
)
Now my question is:
lets say I have one customer has many customer_contacts like this
customer
id name email
1 john john#example.com
and customer_contacts is like this (first row)
id customer_id first_name last_name
1 1 john doe
2 1 johnp pual
like this
So here I want to get all the contact details count for the id john. So can some one tell me how to get that?
Any help and suggestions will be really appreciable. Thanks
If the id is already known (as suggested by the question, it would be a plain
SELECT COUNT(*) from customer_contacts
WHERE customer_contacts.id = 1;
You just need to know the number of contactacs for the customer John, right?
SELECT COUNT(*)
FROM customer cus INNER JOIN customer_contacts con ON cus.id = con.customer_id
WHERE cus.name = 'john'
Nevertheless, It would be better if you know the id of John. Your query would be this:
SELECT COUNT(*)
FROM customer_contacts
WHERE customer_id = 1
Simply join both tables and use count() with group by c.id use where to filter records
select c.*,
count(*) total_contacts
from customer c
left join customer_contacts cc on(c.id = cc.customer_id)
group by c.id
Fiddle Demo

Pretty basic SQL query involving count

Let's say I have the following schema
Company:
-> company_id
-> company_name
Building_to_company:
-> building_id
-> company_id
So each building has its own id as well as a company id which relates it to a single company.
the following query gives two columns -- one for the company name, and then its associated buildings.
SELECT company.company_name, building_to_company.building_id
FROM company, building_to_company
WHERE company.company_id = building_to_company.company_id;
The returned table would look something like this:
Company Name | Building Id
Smith Banking 2001
Smith Banking 0034
Smith Banking 0101
Smith Banking 4055
Reynolds 8191
TradeCo 7119
TradeCo 8510
So that's all simple enough.
But I need to do something a bit different. I need 2 columns. One for the company name and then on the right the number of buildings it owns. And then for a little extra challenge I only want to list companies with 3 or less buildings.
At this point the only real progress I've made is coming up with the query above. I know I some how have to use count on the building_id column and count the number of buildings associated with each company. And then at that point I can limit things by using something like WHERE x < 4
You've basically got it in words already. Assuming company_name is unique, all you have to add to your explanation to get it to work is a GROUP BY clause:
SELECT company.company_name, COUNT(building_to_company.building_id)
FROM company
INNER JOIN building_to_company
ON company.company_id = building_to_company.company_id
GROUP BY company.company_name
(SQL Fiddle demo of this query in action)
To limit it to companies with 3 or less buildings, the key is you have to use a HAVING clause and not WHERE. This is because you want to filter based on the results of an aggregate (COUNT); simply put, WHERE filters come before aggregation and HAVING come after:
SELECT company.company_name, COUNT(building_to_company.building_id)
FROM company
INNER JOIN building_to_company
ON company.company_id = building_to_company.company_id
GROUP BY company.company_name
HAVING COUNT(building_to_company.building_id) < 4
(SQL Fiddle demo of this query in action)
I think you want something like this
SELECT c.company_name, count(b.building_id)
FROM
company as c,
building_to_company as b
WHERE c.company_id = b.company_id
GROUP BY c.company_name;
Use the Below SQL-statement to find the company name with its own building count in descending order.
SELECT company.company_name, count(building_to_company.building_id)
FROM company (nolock), building_to_company(nolock)
WHERE company.company_id = building_to_company.company_id
group by company.company_name
having count(building_to_company.building_id)<=3
order by count(building_to_company.building_id) desc
Kindly let me know if you have any issue. Thanks

Add column to MySQL result

I'm trying to add a column to a Mysql result using a subquery,
Suppose i have a table 'Cars' and a table 'Cars usage'
Table Cars has a column "serial_number" and the Cars usage table has a column "serial_number" as well:
So i wanna generate a result with the car name as first column and car usage as second:
Table cars:
-model
-serial_number
Table carsusage
-date
-serial_number
What i would like to achieve would look like so:
Model | Usage count
--------------------
|bar | 1500 |
|foo | 700 |
Ideally i need a sub-query, that, while querying the cars table, spits a query to the Cars usage table counting:
SELECT model, serial_number AS sn,(SELECT COUNT(serial_number) FROM cars_usage WHERE serial_number=sn) FROM cars;
So basically i would like to use the serial_number AS sn as a local variable and add the result of the count operation as second column.
Any advice?
No that much experience with querying a db here.
Thx
If you want usage per serial number:
select model, serial_number, count(*) from cars inner join carsusage on cars.serial_number=carsusage.serial_number where cars.serial_number=$var group by 1,2
or if you want usage per model:
select model, count(*) from cars inner join carsusage on cars.serial_number=carsusage.serial_number where cars.serial_number=$var group by 1
Why not just try something like
SELECT model,
serial_number AS sn,
(SELECT COUNT(serial_number) FROM cars_usage cu WHERE cu.serial_number=c.serial_number)
FROM cars c;
Where you provide aliases for the tables, and then prefix the fields with the aliases.
You could also try a LEFT JOIN (do be carefull of inner join, because if there a no usages, it will not return a 0 entry for that car).
select c.model,
c.serialnumber sn,
count(cu.*)
from cars c LEFT join
carsusage cu on c.serial_number=cu.serial_number
GROUP BY c.model,
c.serialnumber

MySQL How do I count the number of occurences of each ID?

It may be difficult to explain what I am after, apologies if the question is vague.
I have a table which associates products with keywords using IDs
So I may have product IDs, 2,3,4,5 associated with Keyword id 14
and product IDs 3,6,9 associated with Keyword id 15
My question is How do I count and store the total for those IDs associated with Keyword 14 and for those IDs associated with Keyword 15 and so on (New Keywords added all the time)?
MY SQL so far:
select products_keyword_categories.key_cat_name
from products_keyword_to_product
inner join products_keyword_categories
on products_keyword_categories.key_cat_id = products_keyword_to_product.key_cat_id
group by products_keyword_categories.key_cat_name
Many thanks in advance for any advice. Also, if there is any terminology that will aid me in further research via a Google search that would also be most welcome.
Edit to add: In the example above the table containing the associations is products_keyword_to_product - I inner join the other table to return the Keyword name.
Edit to add (2): Sorry I was afraid my question would be vague.
If I wanted to just count all the products using keyword ID 14 I would use COUNT() AS - As mentioned in the answers but I also need to count the number of products using Keyword ID 15 and Keyword ID 16 etc. - Hope that makes more sense.
select key_cat_name ,count(*)
from products_keyword_categories pkc
inner join products_keyword_to_product ptk on pkc.id=ptk.key_id
group by id;
select cat.key_cat_name, count(*) from
products_keyword_categories cat inner join products_keyword_to_product prod
on prod.key_cat_id=cat.key_cat_id
group by cat.key_cat_name
Edit:
select cat.key_cat_name, prod_assoc.product_id, count(*) from
products_keyword_categories cat inner join products_keyword_to_product prod_assoc
on prod_assoc.key_cat_id=cat.key_cat_id
group by cat.key_cat_name,prod_assoc.product_id
Assuming your tables structure is like this:
products_keyword_categories
key_cat_id key_cat_name
1 Electronics
2 Toys
3 Software
products_keyword_to_product
key_cat_id product_id
1 1
2 1
3 2
1 2
products
product_id name
1 Product A
2 Robot
Edit 2:
Try this
SELECT key_cat_name, product_id, COUNT(*)
FROM
(select cat.key_cat_name, prod_assoc.product_id from
products_keyword_categories cat inner join products_keyword_to_product prod_assoc
on prod_assoc.key_cat_id=cat.key_cat_id) as tbl
GROUP BY key_cat_name, product_id
Edit 3:
The query above is made of 2 parts:
The inner part:
(select cat.key_cat_name, prod_assoc.product_id from
products_keyword_categories cat inner join products_keyword_to_product prod_assoc
on prod_assoc.key_cat_id=cat.key_cat_id)
Which gives 1 row per combination of product_id and key_cat_name.
The outer part:
SELECT key_cat_name, product_id, COUNT(*)
FROM (...) as tbl
GROUP BY key_cat_name, product_id
Which operates on the results of the inner part (as tbl), counting how many times a combination of key_cat_name and product_id appears on the inner part.
Check this: Subqueries in MySQL, Part 1
You are almost there, you just need to add the following:
select count(products_keyword_to_product.id), products_keyword_categories.key_cat_name
...
the rest is correct
Updated Answer:
SELECT COUNT(*), reference_field FROM table WHERE...
HAVING field=value
GROUP BY field
For aggregate conditions you must use HAVING

MYSQL PHP count lines in two tables with one query

I would like to count entries (lines) from two tables WHERE (in both) user_id is 12 and club is 5,8,19. I need to receive values (or array it does not matter) for each club, example (5=>24, 8=>78, 19=>56). How can I write this query please?
thank you.
Assume your tables are: user and club.
SELECT c.club_id, COUNT(*)
FROM user u, club c
WHERE u.user_id = 12
AND c.club_id IN (5,8,19)
AND u.club_id = c.club_id
GROUP BY c.club_id
SELECT COUNT(*) as num_rows FROM my_table WHERE user_id = 12 AND club_id in (5,8,19) GROUP BY club_id