如何使用SQL组筛选具有最大日期值的行

时间:2014-06-10 11:40:51

标签: sql group-by having-clause

我有下表

CREATE TABLE Test
    (`Id` int, `value` varchar(20), `adate` varchar(20))
;

INSERT INTO Test
    (`Id`, `value`, `adate`)
VALUES
    (1, 100, '2014-01-01'),
    (1, 200, '2014-01-02'),
    (1, 300, '2014-01-03'),
    (2, 200, '2014-01-01'),
    (2, 400, '2014-01-02'),
    (2, 30 , '2014-01-04'),
    (3, 800, '2014-01-01'),
    (3, 300, '2014-01-02'),
    (3, 60 , '2014-01-04')
;

我想要实现仅选择具有最大日期值的Id的结果。即

Id,value,adate

 1, 300,'2014-01-03'     
 2, 30 ,'2014-01-04'     
 3, 60 ,'2014-01-04'

如何使用group by实现此目的?我做了如下但不起作用。

Select Id,value,adate
from Test
group by Id,value,adate
having adate = MAX(adate)

有人可以帮助查询吗?

4 个答案:

答案 0 :(得分:11)

选择每个ID的最大日期。

select id, max(adate) max_date
from test
group by id

加入其中以获得其余的列。

select t1.*
from test t1
inner join (select id, max(adate) max_date
            from test
            group by id) t2
on t1.id = t2.id and t1.adate = t2.max_date;

答案 1 :(得分:3)

请尝试:

select 
  * 
from 
  tbl a
where 
  a.adate=(select MAX(adate) from tbl b where b.Id=a.Id)

答案 2 :(得分:3)

如果您使用的是具有分析功能的DBMS,则可以使用ROW_NUMBER:

SELECT  Id, Value, ADate
FROM    (   SELECT  ID,
                    Value,
                    ADate,
                    ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Adate DESC) AS RowNum
            FROM    Test
        ) AS T
WHERE   RowNum = 1;

否则,您需要按ID加入累计最大日期,以便将Test的结果过滤到日期与该ID的最大日期匹配的结果

SELECT  Test.Id, Test.Value, Test.ADate
FROM    Test
        INNER JOIN
        (   SELECT  ID, MAX(ADate) AS ADate
            FROM    Test
            GROUP BY ID
        ) AS MaxT
            ON MaxT.ID = Test.ID
            AND MaxT.ADate = Test.ADate;

答案 3 :(得分:-1)

我会尝试这样的事情

Select  t1.Id, t1.value, t1.adate
from    Test as t1
where   t1.adate = (select max(t2.adate) 
                    from Test as t2
                    where t2.id = t1.id)