Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - How to select a row having a column with max value

Tags:

sql

oracle

date                 value  18/5/2010, 1 pm        40 18/5/2010, 2 pm        20 18/5/2010, 3 pm        60 18/5/2010, 4 pm        30 18/5/2010, 5 pm        60 18/5/2010, 6 pm        25  

i need to query for the row having max(value)(i.e. 60). So, here we get two rows. From that, I need the row with the lowest time stamp for that day(i.e 18/5/2010, 3 pm -> 60)

like image 477
Abhishek Avatar asked May 18 '10 02:05

Abhishek


People also ask

How do I find the maximum value of a row in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).

How do I select a row from a specific value in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.


2 Answers

Keywords like TOP, LIMIT, ROWNUM, ...etc are database dependent. Please read this article for more information.

http://en.wikipedia.org/wiki/Select_(SQL)#Result_limits

Oracle: ROWNUM could be used.

select * from (select * from table  order by value desc, date_column)  where rownum = 1; 

Answering the question more specifically:

select high_val, my_key from (select high_val, my_key       from mytable       where something = 'avalue'       order by high_val desc) where rownum <= 1 
like image 114
Sujee Avatar answered Sep 22 '22 19:09

Sujee


Analytics! This avoids having to access the table twice:

SELECT DISTINCT        FIRST_VALUE(date_col)  OVER (ORDER BY value_col DESC, date_col ASC),        FIRST_VALUE(value_col) OVER (ORDER BY value_col DESC, date_col ASC) FROM   mytable; 
like image 31
Jeffrey Kemp Avatar answered Sep 23 '22 19:09

Jeffrey Kemp