我有下表:
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
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个查询,该查询执行以下操作:
以下查询给出团队和日期:
select team, min(date)
from my_table
group by team
Run Code Online (Sandbox Code Playgroud)
但我怎样才能检索到这个名字呢?我尝试了以下查询,但现在我得到了所有行(我理解,因为分组没有执行任何操作,因为现在所有行都是唯一的):
select name, team, min(date)
from my_table
group by team, name
Run Code Online (Sandbox Code Playgroud)
进行自连接,使用第一个查询作为子查询来查找每个团队的第一个日期:
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
Run Code Online (Sandbox Code Playgroud)
如果团队第一次约会时有两个名字,将返回两个名字。
如果您只想每个团队一行,即使该日期有两个名字,您也可以做另一个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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2396 次 |
| 最近记录: |