简体   繁体   English

SQL-分组依据,保留最早的一行

[英]SQL - group by, keep earliest row

I have following table: 我有下表:

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

I am trying to create a query which does: 我正在尝试创建一个查询,该查询可以:

  • one row per team, so we groupe on the team 每个团队一行,所以我们将团队分组
  • select that row which happened first, so we are aggregating on min(date) 选择最先发生的那一行,所以我们在min(date)上进行汇总

The following query give the team and the date: 以下查询提供了团队和日期:

select   team, min(date)
from     my_table
group by team

But how can I also retrieve the name? 但是我怎么也可以找回名字呢? I tried following query, but now I get all rows (which I understand, because the grouping does nothing, as all rows are unique now): 我尝试了以下查询,但是现在我得到了所有行(据了解,因为分组不执行任何操作,因为所有行现在都是唯一的):

select   name, team, min(date)
from     my_table
group by team, name

Do a self join, where you use your first query as sub-query to find each team's first date: 进行自我联接,在该联接中,您可以使用第一个查询作为子查询来查找每个团队的首次约会:

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

Will return both names if there are two names on a team's first date. 如果团队的首次约会有两个名字,将返回两个名字。

If you just want one row per team, even if that date has two name, you can do another GROUP BY , or simply NOT EXISTS : 如果您只希望每个团队一行,即使该日期有两个名字,您也可以执行另一个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))
SELECT min(NAME)
    ,team
    ,min(DATE)
FROM my_table
GROUP BY team

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM