0

I have a table of 'matches' :

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. How can I calculate previous match of each team? As example, for home team.
  2. How can I calculate previous N-matches of each team?
1
  • 2
    Please add the desired results to clarify what you are looking for. Commented Mar 30, 2014 at 0:16

2 Answers 2

1

Getting the previous matches is challenging, because of the home team/away team split. Instead, let's just focus on one team at a time, by having a separate record for each team.

The following gets the previous matchid for each team in the above table:

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;

You can join in the information about the match, if you like.

Sign up to request clarification or add additional context in comments.

8 Comments

Don't I write simply: select id, match_date, team, lag(id) over (partition by team order by match_date) as prev_matchid ?
@Oleksandr . . . You need a from clause.
I meant FROM matches, without sub-selects
@Oleksandr . . . You have no column called team in matches.
SELECT id, match_date, home_team, lag(id) over (partition by home_team order by match_date) as prev_matchid FROM matches - is there any difference?
|
1

You should be able to use the Max function to get the previous match. By selecting the max date that is less than today, you should be able to get the previous match.

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

To get the previous matches, you can order by match date

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

1 Comment

Won't there be a better to use some window (analytic) functions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.