Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a database table which users id had a foreign id of another user like:

id | refer_id
1.......98
2.......7
3.......4
4.......98
5.......87
6.......13
7.......4
8.......4

I want to check the whole table and count that there's 2(98),1(7),3(4),1(13) and so on.
I am new to database and confuse how the query going to work.
Posted
Comments
DinoRondelly 15-Apr-13 17:23pm    
What have you tried?

1 solution

Try this:
SQL
SELECT refer_id, COUNT(refer_id) AS CountOfReferId
FROM YourTable
GROUP BY refer_id
ORDER BY refer_id


More about: Aggregate functions - MySQL 5.0 Reference[^]
MySQL aggregate functions[^]

To get refer_id's where COUNT(refer_id)>=4
SQL
SELECT refer_id, COUNT(refer_id)
FROM Table1
GROUP BY refer_id
HAVING COUNT(refer_id)>=4


To get SUM(above)
SQL
SELECT SUM(T.CountOfReferId) AS SumOfCountReferId_4
FROM (
    SELECT refer_id, COUNT(refer_id) AS CountOfReferId
    FROM Table1
    GROUP BY refer_id) AS T
WHERE T.CountOfReferId >=4
 
Share this answer
 
v3
Comments
Richard C Bishop 15-Apr-13 17:30pm    
Nice and simple.
Maciej Los 15-Apr-13 17:31pm    
Thank you, richcb ;)
Yafa Su 16-Apr-13 9:33am    
sorry for the late reply, I will give a try
Yafa Su 16-Apr-13 9:39am    
Nice thanks it's what I am looking for :)
Maciej Los 16-Apr-13 9:57am    
You're welcome ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900