Click here to Skip to main content
15,887,328 members
Articles / Database Development / SQL Server / SQL Server 2014
Tip/Trick

A Simple and Another Way to Find Rows on n’th Maximum Number from a Table

Rate me:
Please Sign up or sign in to vote.
4.71/5 (5 votes)
23 Dec 2015CPOL 8.8K   6   2
A simple tip/trick to get rows on n’th maximum number from a table

Introduction

It's a very simple trick to get rows on nth maximum number from a table. In this tip, I used common table expression (CTE) and DENSE_RANK() function. To know more about CTE, click this link and for DENSE_RANK(), click this link.

Using the Code

A simple code snippet is given below:

SQL
    --START TO GET N'TH HIGHEST NUMBER/SALARY

DECLARE @g_query        AS VARCHAR(256)
DECLARE @g_nth_highest  AS INT
DECLARE @g_nth_row      AS INT

SET @g_nth_height = 7;
SET @g_nth_row = 3;

SET @g_query =
    'WITH CTE_RESULT AS
        (
            SELECT ct_salary, DENSE_RANK() OVER
                (
                    ORDER BY ct_salary DESC
                )   AS  DENSERANK_RESULT FROM T_EMPLOYEE
        )
    SELECT TOP '+ CONVERT(VARCHAR, @g_nth_row) + _
    ' ct_salary AS SALARY FROM CTE_RESULT WHERE CTE_RESULT.DENSERANK_RESULT =' + _
    CONVERT(VARCHAR, @g_nth_highest);

    EXEC(@g_query)
-- END

Conclusion

I hope you guys get the scenario and this might be helpful to you. Enjoy!

History

  • Saturday, December 22nd, 2015: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
BugCheck your work please Pin
Carlyle Miersma28-Dec-15 2:12
professionalCarlyle Miersma28-Dec-15 2:12 
GeneralRe: Check your work please Pin
Md. Marufuzzaman28-Dec-15 3:18
professionalMd. Marufuzzaman28-Dec-15 3:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.