简体   繁体   中英

SQL: Select an item in one column based on the other column's value

I have a table that looks like this:

+-----+----+
|A    |B   |
+-----+----+
|    1|   0|
|    2|   1|
|    2|   1|
|    2|   1|
|    2|   2|
|    3|   1|
|    4|   1|
|    5|   1|
|    5|   2|
|    6|   2|
|    7|   2|
|    8|   2|
+-----+----+

I want to select values of A, where the value of B is the lowest. but want to keep the repetitions. Say I have 3 pairs such that (4,5),(4,5),(4,6), I want the result to be (4,5), (4,5).

For the above table, I would like the output to be

+-----+----+
|A    |B   |
+-----+----+
|    1|   0|
|    2|   1|
|    2|   1|
|    2|   1|
|    3|   1|
|    4|   1|
|    5|   1|
|    6|   2|
|    7|   2|
|    8|   2|
+-----+----+

I was trying to do something like this, but I'm lost!

SELECT t1.A, t1.B from table t1 JOIN table t2
WHERE t1.B >= t2.B
ORDER BY B DESC

Any leads appreciated!

This should work:

select t1.* from mytable t1
join
    (select A, min(B) as B from mytable group by A) t2
on t1.A = t2.A and t1.B = t2.B
SELECT
a.A, a.B
FROM table1 a WHERE B=(select MIN(b) FROM table1)
ORDER BY B DESC

You can use subquery. First identify all the columns that are satisfying the condition. Then filter out the records using where.

select A,B from(
        select A,B, case when B<A then 'Y' else 'N' end as C from table)
        where C = 'Y'

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