从每个主键的 table 中获取顶部数据

Fetching top data from the table for each primary key

我有一系列外键,每个键构成了table中的不止一行。如何只获取符合指定条件的第一行?

我有table这样的

ID    NAME      DATE
----------------------
1     abc       5/10/15
1     abc       6/11/15
2     pqr       7/11/15
2     pqr       8/10/15
3     xyz       9/12/15

我要输出成这样

条件是日期 > 5/11/15 和 ID 在 (1,2)

ID   NAME   DATE
-----------------
1    abc    6/11/15
2    pqr    7/11/15

使用 NOT EXISTS 到 return 行,只要没有其他行具有相同的名称和更早的日期:

select t1.*
from tablename t1
where not exists (select * from tablename t2
                  where t2.name = t1.name
                    and t2.date < t1.date
                    and t2.date > '5/11/15' and t2.ID in (1,2))
  and t1.date > '5/11/15' and t1.ID in (1,2)

JOIN替代方案,也许更好MySQL答案:

select t1.*
from tablename t1
    join (select name, min(date) from tablename
          where date > '5/11/15' and t2.ID in (1,2)
          group by name) as t2
      on t1.name = t2.name and t1.date = t2.date
where t1.date > '5/11/15' and t1.ID in (1,2)

核心SQL-99.

您可以使用 row_number() 做您想做的事。我不确定你到底想要什么。我最好的猜测是获取满足条件的最小日期的行:

select t.*
from (select t.*,
             row_number() over (partition by id order by date) as seqnum
      from t
      where date > '2015-11-05' and id in (1, 2)
     ) t
where seqnum = 1;