How to Get Top 2 values in Sql Query [Resolved]

Posted by Jayakumars under C# on 12/9/2016 | Points: 10 | Views : 1349 | Status : [Member] [MVP] | Replies : 1
Create Table TestDemo
ID int,
amount decimal(6,2)

Insert into TestDemo values(10,1500)
Insert into TestDemo values(9,1000)
Insert into TestDemo values(9,NULL)
Insert into TestDemo values(8,50)
Insert into TestDemo values(7,30)
Insert into TestDemo values(6,10)

select * from TestDemo

-- I need how to get top 2 records only 2 separate variable in sql server
--like this

-- in my sql server declare value this

---Declare @TOP1 int ,@Top2 int
--I need set value here
-- set @TOP1=1500 -- for id = 10
-- set @TOP2=1000 --- for id = 9 is not null
-- How will do this

Mark as Answer if its helpful to you


Posted by: A2H on: 12/9/2016 [Member] [MVP] Silver | Points: 50


You can try with one of the below options.
Using IN operator

SELECT * FROM dbo.TestDemo td WHERE td.amount IN(@TOP2,@TOP1) AND td.amount IS NOT NULL

Using Union
SELECT * FROM dbo.TestDemo td WHERE td.amount=@TOP1
SELECT * FROM dbo.TestDemo td WHERE td.amount=@TOP2 AND td.amount IS NOT NULL

My Blog

Jayakumars, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response