我试图与此question
相反我需要从分组记录中获取最小值,因此,从链接的问题中获取相同的信息,来自
ID | Person | Group | Age
---
1 | Bob | 1 | 32
2 | Jill | 1 | 34
3 | Shawn | 1 | 42
4 | Jake | 2 | 29
5 | Tom | 2 | 28
6 | Paul | 2 | 36
7 | Laura | 2 | 39
8 | Julie | 2 | 28
期望的结果集:
1 | Bob | 1 | 32
5 | Tom | 2 | 28
我尝试以相反的条件(<而不是>)加入自己的表格但是它不起作用。
不允许重复,如果两个人的年龄相同,则必须退回ID最低的人。
答案 0 :(得分:4)
我会使用where
和相关的子查询来执行此操作:
select p.*
from persons p
where p.age = (select min(p2.age) from persons p2 where p2.group = p.group);
或:
select p.*
from persons p
where p.age = (select p2.age
from persons p2
where p2.group = p.group
order by p2.age desc
limit 1
);
使用id
:
select p.*
from persons p
where p.id = (select p2.id
from persons p2
where p2.group = p.group
order by p2.age desc, id asc
limit 1
);
答案 1 :(得分:0)
这是一种方式(我为了保持理智而改名为其中一列):
SELECT a.*
FROM my_table a
JOIN
( SELECT MIN(id) id
FROM my_table x
JOIN
( SELECT group_id, MIN(age) age FROM my_table GROUP BY group_id) y
ON y.group_id = x.group_id
AND y.age = x.age
GROUP
BY x.group_id
, x.age
) b
ON b.id = a.id;