2

I'm searching a SQl query that gives me all values that have their max() at a certain time.

This is my simplified table:

    +---------+-------+-------+
    | name    | value | month |
    +---------+-------+-------+
    |  joe    |   10  | jan   |
    |  olivia |   300 | jan   |
    |  tim    |   10  | jan   |
    |  joe    |   100 | feb   |
    |  olivia |   50  | feb   |
    |  tim    |   100 | feb   |
    +---------+-------+-------+

This is how I would describe my query:

SELECT name FROM table WHERE MAX(value) is in 'jan'

This should be my result:

olivia

Best Joerg

JoergP
  • 1,349
  • 2
  • 13
  • 28

2 Answers2

4

Here is one method:

select t.*
from t
where t.value = (select max(t2.value) from t t2 where t2.name = t.name) and
      t.month = 'jan';

You can also use window functions:

select t.*
from (select t.*,
             max(value) over (partition by name) as max_value
      from t
     ) t
where value = max_value and month = 'jan'
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

you need below

SELECT name FROM table WHERE value = (select max(value) from table where month='jan') and month='jan'

incase of month wise max

select t1.* from table_name t1
where value = (select max(value) from table_name t2 where t1.month=t2.month)
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63