Skip to content
Advertisement

T-SQL, how to get top three maximum values and if repeats, include them?

As stated in the title, I wish to select the top 3 values, and if the value that is counted repeats, include it too.

This output returns all of the maximum values, ex:

If I were to use TOP 3, to choose TOP 3, with the following SQL:

It would return the following:

The desired output in this situation would be to do what I want is:

I understand that the TOP 3 limits to only three results, but I cannot seem to figure out an approach how to add if it is repeated.

Furthermore, if I were to include WITH TIES:

The output in this case is:

Upon testing, if I choose TOP 5 the 2090 value appears, but I wish to do the same with TOP 3 if possible so that the output is as-is:

Advertisement

Answer

DENSE_RANK() is your friend:

Presumably you could merge the two CTEs together, but I am never sure exactly how the OVER functions interact with GROUP BY, so I did it this slightly longer way.

Personally I can say that since ROW_NUMBER(), RANK() and DENSE_RANK() windowing functions came out in T-SQL (2008?) I hardly ever use TOP any more.

Edited – the DENSE_RANK() To show the top results.

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