gpt4 book ai didi

mysql - SQL - 选择两列中的最大值

转载 作者:行者123 更新时间:2023-11-30 00:59:00 25 4
gpt4 key购买 nike

我有一个表,我需要从中选择 max(bar)对于每个 foo并且排除任何记录,如果两者 foobar低于foobar另一条记录。

数据:

+------+------+
| foo | bar |
+------+------+
| 5 | 30 |
| 5 | 40 |
| 6 | 60 |
| 6 | 65 |
| 6 | 95 |
| 7 | 10 |
| 7 | 30 |
+------+------+

预期结果:

+------+----------+
| foo | max(bar) |
+------+----------+
| 6 | 95 |
| 7 | 30 |
+------+----------+

我被困住了

+------+----------+
| foo | max(bar) |
+------+----------+
| 5 | 40 |
| 6 | 95 |
| 7 | 30 |
+------+----------+

我尝试了以下查询的不同变体,但没有成功。

select foo, max(bar) from mytable
group by foo
order by foo, bar;

最佳答案

您的查询即将完成。你只需要一个合适的过滤条件。这是使用 not contains 进行过滤的一种方法:

select foo, max(bar)
from mytable t
where not exists (select 1
from mytable t2
where t.foo < t2.foo and t.bar < t2.bar
)
group by foo
order by foo;

关于mysql - SQL - 选择两列中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20305876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com