简体   繁体   中英

How to select rows where a specific column has the highest value and another column has a specific value

I am looking to select the following rows from a table where the following constraints are met:

I have been messing with joins on itself (selecting max version of this if idb = x in a subquery) but have had no luck

For example:

idb = x if va of a specific ida is the max va for that ida and idb is x, then include it

ida     |    idb     |     va
--------------------------------
abc          x             1
abc          y             2
abc          x             3
def          x             1
xyz          x             1
xyz          x             2
xyz          z             3

Result:

ida     |    idb     |     va
--------------------------------
abc          x             3
def          x             1

For the previous example,

abc is included because the highest version of va (3) is in a row where idb=x

def is included because the highest version of va(1) is in a row where idb = x

xyz is NOT included because the highest version of xyz (va=3) has a value of idb=z

If I understand correctly, you want the rows where the maximum version for a given ida has an idb value of 'x' .

If so:

select t.*
from (select t.*,
             max(version) over (partition by ida) as max_version
      from t
     ) t
where version = max_version and idb = 'x';

You can use row_number() and filter in the outer query on idb = 'x' :

select ida, idb, va
from (

    select 
        t.*,
        row_number() over(partition by ida order by va desc) rn
    from mytable t
) x
where rn = 1 and idb = 'x'

Demo on DB Fiddle :

ida | idb | va
:-- | :-- | -:
abc | x   |  3
def | x   |  1

The simplest code would be:

select t.ida, t.idb, t.va
  from your_table t
 where t.idb = 'x'
   and t.va = (select max(sub_qry.va) 
                 from your_table sub_qry
                where sub_qry.ida = t.ida)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM