0

想象一下我有下表:

NAME DATE OTHER_CONTANT

'A' '2012-06-05' 'baz'
'A' '2012-06-04' 'bar'
'B' '2012-06-05' 'foo'
'C' '2012-06-05' 'bla'
'C' '2012-06-04' 'blah'
'C' '2012-06-06' 'bleh'

现在我想过滤此表以仅包含具有唯一名称和最早日期的行:

'A' '2012-06-04' 'bar'
'B' '2012-06-05' 'foo'
'C' '2012-06-04' 'blah'

我正在考虑使用 GROUP BY 语句,但是使用 GROUP BY 我只能得到一列作为结果,我想得到整行。有关如何进行此过滤的任何建议?

4

5 回答 5

3

您可以使用以下内容:

select m.name, m.date, m.other_constant 
  from mytable m
  join (select name, min(date) min_date from mytable group by name) n
    on m.name = n.name and m.date = n.min_date

另请参阅SQLfiddle

于 2012-06-13T07:46:54.460 回答
2

以下 SQL 创建所有不同名称的列表。然后对于每个名称,它会查找具有最新日期的条目。

select  *
from    (
        select  distinct name
        from    YourTable
        ) names
join    YourTable yt1
on      yt1.name = names.name
        and yt1.date =
        (
        select  date
        from    YourTable yt2
        where   yt2.name = yt1.name
        order by
                date
        limit   1
        )

使用 beny23 的 SQL Fiddle 的实时示例。

于 2012-06-13T07:37:41.743 回答
1

两个查询都可以完美运行。

SELECT * 
FROM   MyTable a 
       INNER JOIN (SELECT name, 
                          Min(date) AS date 
                   FROM   MyTable 
                   GROUP  BY name) b 
               ON a.name = b.name 
                  AND a.date = b.date

或者

SELECT a.* 
FROM   mytable a 
       LEFT JOIN mytable b 
              ON a.name = b.name
                 AND a.date > b.date 
WHERE  b.name IS NULL 
于 2012-06-13T07:34:39.483 回答
0
select *
from (
   select name, min(date) as mindate, other_contact
   from table_name group by name
   ) as x
   inner join table_name as f 
   on f.name = x.name and f.date= x.mindate; 
于 2012-06-13T07:42:17.783 回答
0
SELECT
    a.name,
    a.date,
    b.other_contant
FROM
    (
        SELECT
            name,
            MIN(date) AS date,
        FROM
            yourtable
        GROUP BY 
            name
    ) a
INNER JOIN
    yourtable b ON a.name = b.name AND a.date = b.date
于 2012-06-13T08:06:24.397 回答