Click here to Skip to main content
15,884,889 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
ID Name price
1 ram 1000
2 ram 3000
3 raj 2000
4 krish 1000
5 sai 8000
6 raj 6000
7 ram 2000

In that table , i want to find out the second maximum price for 'ram'.
How to find it.

Thanks in Advance
Posted

Like this:

SQL
SELECT MAX(Price) FROM MyTable
WHERE Price NOT IN (SELECT MAX(Price) FROM MyTable WHERE Name = 'Ram')
AND  Name = 'Ram'
 
Share this answer
 
v2
Comments
Maciej Los 24-Nov-14 6:30am    
Manas, OP wants to get second max value!
Manas Bhardwaj 24-Nov-14 8:51am    
Hi Maciej,

Yes, but this should be ok. The subquery removes the maximum and thus you get second max.

or did I miss something?
Maciej Los 24-Nov-14 9:22am    
OK, i see it now.
+5
Try:
SQL
WITH myTableWithRows AS (
    SELECT (ROW_NUMBER() OVER (ORDER BY myTable.price DESC)) as row,*
    FROM myTable)
SELECT * FROM myTableWithRows WHERE row = 2
 
Share this answer
 
Comments
Maciej Los 24-Nov-14 6:31am    
+5!
[EDIT]
You forgot to add Partition by [Name] and where statement [Name]='Ram'. Please, improve your answer, Paul.
RossMW 24-Nov-14 20:33pm    
Interesting... but what happens when there are two or more records with the max price. It comes down to the exact meaning of second maximum price. May need to distinct the prices.
Here is another one, using top:
SQL
select top 1 *
from (
    select top 2 *
    from theTable
    where lower(name) = 'ram'
    order by price desc
) MaxPriceTop2
order by price asc
;

And another one using the OFFSET FETCH clause, MSSqlServer 2012+:
SQL
select *
from theTable
where lower(name) = 'ram'
order by price desc
    offset 1 rows
    fetch next 1 rows only
;
 
Share this answer
 
v2
SQL
WITH myTableWithRows AS (
        SELECT (ROW_NUMBER() OVER ( PARTITION BY NAME ORDER BY myTable.price DESC)) as row,name ,*
        FROM myTable)
    SELECT * FROM myTableWithRows WHERE row = 2 and name='ram'
 
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