Ponting
Ponting

Reputation: 2246

How to fetch FIRST row when there are same value for column in case of finding MIN value (SQL)

In My table ,

One column has following values :

Row Column
 1   90
 2   95
 3   99
 4   90
 5   92
 6   90

Now I want to fetch min value for above column but fetch top row if there are more than one row which have same minimum value. How can I do this ?

As illustrated in above example : I want to min value(90) but first row.

Any help will be appreciated.

Upvotes: 0

Views: 1705

Answers (4)

Mani Kandan
Mani Kandan

Reputation: 11

SELECT TOP 1 * FROM m_test WHERE row IN ( SELECT row FROM m_test b WHERE b.column_cnt IN (SELECT min(a.column_cnt) FROM m_test a)) ORDER BY row ASC

Upvotes: 0

Vikas Rana
Vikas Rana

Reputation: 1999

use this query select Row, min(column) from your_table order by Row desc limit 1

Upvotes: 1

Ravinder Reddy
Ravinder Reddy

Reputation: 24002

If you want to fetch the records in the same order of rows inserted, you can just use:

select Row, min(Column) from my_table group by Column;  

If you want to fetch sorted rows as well:

select Row, min(Column) from my_table group by Column order by column, row;  

And if you are looking only first row of the results, just append the query with limit 1;

Upvotes: 0

Remus Rusanu
Remus Rusanu

Reputation: 294297

MIN is also the one that will sort first in ORDER. So simply specify the order you want and take first one:

WHERE Column is NOT NULL
ORDER BY Column, Row LIMIT 1

Upvotes: 1

Related Questions