Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL get max value

Tags:

sql

I have a table called Filter with the following columns:

FilterID    ViewID  Rank1
3              3      1
220           94      1
221           94      2


I need to get the FilterID with a maximum Rank for each ViewID.

The result should be:

FilterID 
3
221

For ViewID 94 Rank1 is 2, hence the value is 221.

Thank you

like image 647
Ramya Avatar asked Feb 03 '26 15:02

Ramya


2 Answers

You didn't state your DBMS so this is ANSI SQL (which works on nearly all modern DBMS)

select FilterID
from (
  select FilterID, 
         ViewID, 
         Rank1,
         max(Rank1) over (partition by ViewID) as max_rank
  from Filter
) t
where Rank1 = max_rank;

In shortcut,

 select max(FilterID)
  from Filter
group by ViewID
like image 21
AK47 Avatar answered Feb 05 '26 04:02

AK47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!