In this tutorial you will learn a query to find second highest value of column in a table. I am using Northwind database table “Order” for this tutorial.
First have a look at the query to find the first highest value of the column. I have used max() built in function of MS SQL server to find the highest value of the column.
-- First Highest Value
select max(orderid) as HighestValue from orders
Now I am going to write a query for second highest value of column “orderid” which is very easy.
-- Second Highest Value
select max(orderid) as SecondHighestValue from orders where orderid not in (select max(orderid) as HighestValue from orders)
I just use the first query as subquery and find the highest value after that I use not in to find the second highest value. Here is another query to find the second highest value of a column.
-- Second Highest Value
SELECT orderid as SecondHighestValue FROM orders WHERE orderid =( SELECT MAX(orderid) FROM orders WHERE orderid<(SELECT max(orderid) FROM orders))
Hope it will be helpful for you.
No comments:
Post a Comment
Please do not enter spam links.