In facebook, there is afollowtable with two columns:followee,follower.

Please write a sql query to get the amount of each follower’s follower if he/she has one.

For example:

Explaination:
Both B and D exist in the follower list, when as a followee, B’s follower is C and D, and D’s follower is E. A does not exist in follower list.
Note:
Followee would not follow himself/herself in all cases.
Please display the result in follower’s alphabet order.

Analysis


Join 2followtables. Let_followee_of the second table be equal to the_follower_of the first table so that_follower_in the second table is follower’s follower in the first table. Then group by_follower_of the first table and count number of_follower_in the second table for each_follower_in the first table. Finally exclude duplicates and sort by_follower_of the first table alphabetically.

Solution


SELECT f1.follower, COUNT(DISTINCT f2.follower) ASnumFROMfollow AS f1 JOIN follow AS f2 ON f1.follower = f2.followeeGROUPBY f1.follower ORDERBY f1.follower;

results matching ""

    No results matching ""