EchoFool Posted May 28, 2010 Share Posted May 28, 2010 Hey, If a database of users have a field named "ReferredBy" with the user id of the person that they were referred by... im trying to get a query that can then collect the top 20 users who have referred the most people. So i tried Count(ReferredBy) As TotalReferred But then realised without the WHERE clause stateing exactly which ID to count i can't make a simple list like: User1 Referred 10 User4 Referred 7 User2 Referred 3 (DESC order basically). How would i make a query to do that with a count and without actually referencing a precise ID? Link to comment https://forums.phpfreaks.com/topic/203204-count-with-an-order-by/ Share on other sites More sharing options...
fenway Posted May 29, 2010 Share Posted May 29, 2010 why not simply group by referred_by, and order by the count desc, limit 20? Link to comment https://forums.phpfreaks.com/topic/203204-count-with-an-order-by/#findComment-1065004 Share on other sites More sharing options...
EchoFool Posted May 29, 2010 Author Share Posted May 29, 2010 So like : SELECT Count(ReferredBy) AS Total FROM tablename GROUP BY Count(ReferredBy) ORDER BY Total DESC Or is there a better way? Link to comment https://forums.phpfreaks.com/topic/203204-count-with-an-order-by/#findComment-1065031 Share on other sites More sharing options...
fenway Posted May 29, 2010 Share Posted May 29, 2010 Pretty close.. of course, you'll want back to ReferredBy column itself, and LIMIT 10. Link to comment https://forums.phpfreaks.com/topic/203204-count-with-an-order-by/#findComment-1065073 Share on other sites More sharing options...
EchoFool Posted May 29, 2010 Author Share Posted May 29, 2010 What you mean by want back to ReferredBy column itself? Link to comment https://forums.phpfreaks.com/topic/203204-count-with-an-order-by/#findComment-1065142 Share on other sites More sharing options...
fenway Posted May 30, 2010 Share Posted May 30, 2010 Well, how else are you going to identify which users we're talking about? Link to comment https://forums.phpfreaks.com/topic/203204-count-with-an-order-by/#findComment-1065337 Share on other sites More sharing options...
EchoFool Posted May 30, 2010 Author Share Posted May 30, 2010 Oh i see - of course You mean this: SELECT Count(ReferredBy) AS Total,ReferredBy FROM tablename GROUP BY Count(ReferredBy) ORDER BY Total DESC Link to comment https://forums.phpfreaks.com/topic/203204-count-with-an-order-by/#findComment-1065343 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.