I've been looking for a simple SQL query to solve a very simple problem. I have been running a very simple social sharing campaign and we have a mysql database with 2 fields: email and AffiliateID
SELECT
users.Email, users.ID,
users.AffiliateID,
Count(users.AffiliateID) as afid
from users
order by afid desc
When I run this query it only returns 1 record with the correct count only the highest count.
What I would like is a list of all the users sorted by the people who have the most 'affiliateID' records in the database.
That will tell us who to give the first prize in the sharing contest to.
Here are some similar questions in here but those solutions don't seem to apply for this situation.
What I would like is a descending output of all the users in the system RANKED by their parent (sponsor) so we can build something akin to a 'leader board'
Group By Count and Total Count
MySQL: Count total in Group by Query
Thank you for your help!
here's updated query
select u.Email, AffiliateID, count(u.AffiliateID) as afid
from users u
where SiteID=17
group by u.Email
order by afid desc
this generates the image above...
but that's not what I need. What I need is for the 509218 user to show up first and then the count of how many users he's referred followed by the next user 5dd.. then in third place and fourth place would be 471 and 472 with a tie.
You should add group by
(to get results per user) clause:
select u.AffiliateID, count(u.Email) as afid
from users u
group by u.AffiliateID
order by afid desc
If you need more data from your users
table you can join
result of the query below with users
table:
select u.ID, u.Email, t.afid
from users u
join (
select AffiliateID, count(ID) as afid
from users
group by AffiliateID
) t on u.ID = t.AffiliateID
order by t.afid desc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.