Click here to Skip to main content
15,918,889 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello all

i have three columns in table marksheet suppose

test1 with value 70 ,test2 with value 50 and test3 with value 40

now how can i get top two values from sqlserver which will be 70 and 50




thanks in advance

What I have tried:

hello all

i have three columns in table marksheet suppose

test1 with value 70 ,test2 with value 50 and test3 with value 40

now how can i get top two values from sqlserver which will be 70 and 50




thanks in advance
Posted
Updated 18-Apr-17 1:46am

If i understand you correct

CREATE TABLE #test (
    test1 int,
   test2 int,
   test3 int
);
insert into #test (test1, test2, test3) values (70, 50, 30);
insert into #test (test1, test2, test3) values (30, 70, 50);
insert into #test (test1, test2, test3) values (50, 30, 70);
select 
case when test1 >test2 and test1>test3 then test1 when test2>test1 and test2>test3 then test2 else test3 end firstbigger ,
	case when 
		test1 >test2 and test1>test3  then case when test2>test3 then test2 else test3 end 
		when test2>test1 and test2>test3 then case when test1>test3 then test1 else test3 end  
	else case when test2>test1 then test2 else test1 end  end secondbigger

from #test

drop table #test
 
Share this answer
 
An alternative to Solution 1 (which repeats the results for each row in table #test), using the same test setup
SQL
select top 2 * from
(
	select distinct(test1) as datum
	from #test
	union 
	select distinct(test2)
	from #test
	union  
	select distinct(test3)
	from #test
) q
order by 1 desc
I.e. put all of the values of interest into a single query making sure there are no duplicates (distinct and union do this) then order that result and pick the top 2 entries. Results:
SQL
datum
70
50
You could use a CTE instead of the sub-query if you prefer
SQL
;WITH cte as
(
	select distinct(test1) as datum
	from #test
	union 
	select distinct(test2)
	from #test
	union  
	select distinct(test3)
	from #test
) 
select top 2 * from cte
order by 1 desc
If you want the results in the same row but in two columns then you should use PIVOT. There is a neat trick using ROW_NUMBER which will get you the TOP 2 without using that key word:
SQL
;WITH cte as
(
	select distinct(test1) as datum
	from #test
	union 
	select distinct(test2)
	from #test
	union  
	select distinct(test3)
	from #test
)
select * from
(
	select ROW_NUMBER() OVER (ORDER BY datum desc) AS rn, datum 
	from cte
) base
PIVOT (MAX(datum) FOR rn in ([1],[2])) pvt
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900