Skip to content
Advertisement

How to display an individual with highest number of posts and an individual with lowest number of posts at the same time in SQL Server?

Below is the table I have created and I have also inserted values in it:

Now I am trying to solve the following question:

Write a query that displays the team members who have published the highest and lowest number of posts.

This is what I have done:

I received the following result:

enter image description here

I almost got my desired result but the only problem is that it is showing duplicate values. I even tried adding DISTINCT for both username and num_of_posts, and still it is showing duplicate values. I am still not able to figure out why my query logic is returning duplicate values.

How can this issue be fixed ?

Advertisement

Answer

You’re doing a cartesian join between both lists, but there is no correlation between them so you can’t really join them – what if you had 3 users sharing max posts and 1 with min posts – which of the 3 rows matches up to the 1 row?

You probably want something like the following which effectively gives boths separate lists in a single “union”:

You could also tweak it slightly to return just a row for the min and max counts and the users for each:

Which gives:

enter image description here

One other option is to full join between each separate query results using row_number to artificially create a join condition:

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