我有一张名为activities
的桌子,里面有人,运动和这个人参加这项运动的日期。例如:
person | sport | date
--------------------------------
jane | soccer | 09/15/2012
sam | basketball | 09/10/2012
jane | tennis | 09/12/2012
sam | basketball | 09/08/2012
sam | soccer | 09/04/2012
jane | tennis | 09/01/2012
sam | basketball | 08/27/2012
jane | football | 08/23/2012
我需要包含一个人参加运动的最新日期的行。结果将是:
person | sport | date
--------------------------------
jane | soccer | 09/15/2012
sam | basketball | 09/10/2012
jane | tennis | 09/12/2012
sam | soccer | 09/04/2012
jane | football | 08/23/2012
你可以在这里看到,例如,在9/1的Jane打网球的行被排除在外,因为她也参加了9/12的新日期。
这个查询是什么?我更喜欢非子查询答案,但欢迎所有答案。此外,欢迎MySQL和PostgreSQL的答案。
答案 0 :(得分:2)
这是:
select person, sport, max( date) as date
from activities
group by person, sport
答案 1 :(得分:2)
您可以在PostgreSQL中使用row_number()
(请参阅SQL Fiddle with Demo):
select *
from
(
select person, sport, date,
row_number()
over(partition by person, sport order by date desc) rn
from yourtable
) x
where rn = 1