SQL - 选择最多两列

时间:2013-11-30 21:31:25

标签: mysql sql

我有一张表,我需要为每个max(bar)选择foo 如果 <{strong> foobar低于另一条记录的foobar,则会排除任何记录。< / p>

数据:

+------+------+
| 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;

3 个答案:

答案 0 :(得分:1)

您的查询几乎就在那里。您只需要一个合适的过滤条件。以下是使用not exists进行过滤的一种方法:

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;

答案 1 :(得分:1)

带有LEFT JOIN的版本:

SELECT MAX(mt1.bar), mt1.foo 
FROM myTable mt1 
LEFT JOIN myTable mt2 ON (mt1.foo < mt2.foo AND mt1.bar < mt2.bar)
WHERE mt2.foo IS NULL
GROUP BY mt1.foo
;

SQL Fiddle

答案 2 :(得分:-2)

尝试获取子查询中每列的最大值,然后按

尝试您的组
select t1.foo, max(t1.bar) 
from mytable t1, (select max(foo) foo, max(bar) bar from mytable) t2 
where t1.foo = t2.foo 
or t1.bar = t2.bar 
group by foo;