我有以下表格:
name team date
-----------------------------------
John A-team 02-5-2014
Jessica A-team 08-6-2015
David A-team 11-2-2013
Bill B-team 12-5-2017
Nicole B-team 18-1-2010
Brandom B-team 22-9-2012
我正在尝试创建一个查询:
以下查询为团队和日期提供:
select team, min(date)
from my_table
group by team
但我怎样才能找回这个名字?我尝试了以下查询,但现在我得到了所有行(我明白了,因为分组什么都不做,因为现在所有行都是唯一的):
select name, team, min(date)
from my_table
group by team, name
答案 0 :(得分:4)
进行自我加入,您将第一个查询用作子查询,以查找每个团队的第一个日期:
select t1.*
from my_table t1
join
(select team, min(date) min_date
from my_table
group by team) t2 on t1.team = t2.team and t1.date = t2.min_date
如果团队第一次约会有两个名字,则会返回两个名字。
如果您只想要每个团队一行,即使该日期有两个名称,您也可以执行另一个GROUP BY
,或只是NOT EXISTS
:
select t1.*
from my_table t1
where not exists (select 1 from my_table t2
where t2.team = t1.team
and (t2.date < t1.date
or (t2.date = t1.date and t2.name < t1.name))
答案 1 :(得分:0)
SELECT min(NAME)
,team
,min(DATE)
FROM my_table
GROUP BY team