计算PostgreSQL中的上一个日期

时间:2014-03-29 23:57:33

标签: sql postgresql-9.1

我有一个'匹配'表:

id   match_date    home_team  away_team
---------------------------------------
 1   2012-10-01    Milan      Real
 2   2013-01-05    Real       PSG
 3   2013-04-05    Inter      Lacio
 4   2013-07-10    Ajax       Milan
---------------------------------------
  1. 如何计算每支队伍的上一场比赛?例如,对于主队。
  2. 如何计算每个团队之前的N场比赛?

2 个答案:

答案 0 :(得分:1)

您应该可以使用Max功能来获得上一个匹配项。通过选择小于今天的最大日期,您应该能够获得上一场比赛。

Select Max(match_date), home_team, away_team 
from matches 
where match_date < current_date

要获取之前的匹配项,您可以按匹配日期排序

Select Match_date, home_team, away_team 
from matches 
order by match_date desc 
where match_date < current_date

答案 1 :(得分:1)

之前的比赛很有挑战性,因为主队/客场球队分道扬..相反,让我们一次只关注一个团队,为每个团队单独记录。

以下内容获取上表中每个团队的上一个matchid:

select id, match_date, team,
       lag(id) over (partition by team order by match_date) as prev_matchid
from ((select id, match_date, home_team as team, 'home' as which
       from matches
      ) union all
      (select id, match_date, away_team as team, 'away' as which
       from matches
      )
     ) m;

如果您愿意,可以加入有关比赛的信息。