Skip to content
Advertisement

SQL – Counting from distinct pairs

I have a table representing sending msgs between friends on FB:

What is an SQL query to show how many have 1,2,3… friends:

I have tried using a loop, but it just gets too complicated…

Advertisement

Answer

You could use a couple of sub-queries to achieve this by following an approach like this:

  1. List of all unique senders and receivers.
  2. Count of the number of friends per unique sender.
  3. Group the number of friends and count how many occurrences there are.

Here’s some code that shows it working (obviously field names need to change to match your actual table):

Output:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement