简体   繁体   English

SQL-返回与另一列值匹配的一列中的最小值

[英]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? 如何在column4中返回column3中基于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: 加入一个子查询,该子查询计算每个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: 请参阅SQLFiddle ,显示示例数据中的以下输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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