简体   繁体   中英

SQL - return the smallest value in one column that matches the value of another column

How can I return in column4 the smallest number from column3 based on column1?

1   100 1
2   100 1
1   101 2
1   102 4
2   200 19
3   200 19
16  200 19
18  200 19
19  200 19
20  200 19
3   301 28
6   301 28
3   302 29
3   310 30
4   400 31
4   410 32
4   420 33
5   500 34
7   500 34
5   510 35
6   510 35
5   520 36
6   610 37
7   700 38
7   701 39
8   701 39
8   800 40
8   802 41

Thank you!

Join to a subquery that calculates the minimums for each col1:

select a.col1, a.col2, a.col3, mcol3
from mytable a
join (select col1, min(col3) mcol3 from mytable group by col1) b
  on b.col1 = a.col1

See SQLFiddle , showing this output from your sample data:

1   100 1   1
2   100 1   1
1   101 2   1
1   102 4   1
2   200 19  1
3   200 19  19
16  200 19  19
18  200 19  19
19  200 19  19
20  200 19  19
3   301 28  19
6   301 28  28
3   302 29  19
3   310 30  19
4   400 31  31
4   410 32  31
4   420 33  31
5   500 34  34
7   500 34  34
5   510 35  34
6   510 35  28
5   520 36  34
6   610 37  28
7   700 38  34
7   701 39  34
8   701 39  39
8   800 40  39
8   802 41  39

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