简体   繁体   中英

Return records from select based on column value. Oracle

So i do have select witch looks like this:

SELECT * FROM database1 WHERE ID = 3933185

Records witch select returns to me are:

ID          VALUE   ATTR_VALUE
3,933,185   1           1
3,933,185   1           1
3,933,185   1           1
3,933,185   1           2
3,933,185   1           2

As you can see per attr_value column there could be different values, 1 or 2 , nothing more.

So what should i add to make a check, when attr_value exists with value 1 , then it will return records where attr_value = 1 , in other case it will return where attr_value = 2 .

Hope my question is clear.

I think you want:

select t.*
from t
where t.value = (select min(t2.value) from t t2 where t2.id = t.id);

You can also use analytic functions:

select t.*
from (select t.*, min(t.value) over (partition by id) as min_value
      from t
     ) t
where value = min_value;

You could use exists logic here:

SELECT d1.*
FROM database1 d1
WHERE NOT EXISTS (SELECT 1 FROM database1 d2
                  WHERE d1.ID = d2.ID AND d2.ATTR_VALUE > d1.ATTR_VALUE);

If I followed you correctly, you can use analytical functions:

select id, value, attr_value
from (select t.*, rank() over(order by attr_value) rn from mytable t) t
where rn = 1

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