65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.71/5 (5 votes)

Dec 23, 2015

CPOL
viewsIcon

9386

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:

    	--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