I am new to SQL and I’ve been struggling with this example for quite a while now.
I have this table:
So, what is asked from me is to produce a count of the number of recommendations each member has made. Order by number of recommendations. The final result should look something like this:
I really am confused, since the values of column recommendedby
is actually the id
of the member. I don’t know how to "recognize" them as id
and not just some values, count how many recommendations each member has and "connect" them to memid
column to get to needed result.
So far I managed to do this:
SELECT COUNT(recommendedby)
FROM members
GROUP BY recommendedby
But I’m stuck now. I get a counted number of recommendations for each id
, but it’s not connected to actual id
. This is my result.
3
Answers
I think this is what you’re looking for:
Although using subqueries are not very popular and can cause serious performance issues, this is imho the easiest way to learn what you’re doing.
You should use a self-join for this:
The left join will make
r.id
be NULL for members that made no recommendation, andcount
won’t count such NULL values.There are two ways you can go with.
This is pretty simple, all you need to do is put the query you made as SubQuery and Join your table with that.
Hope this can help.