Postgresql

基於前 n 行的總和進行查詢

  • September 6, 2020

我有一個帶有列的足球比賽表:

id,match_date,team1_id,team2_id,score_team1,score_team2

我需要一個結果顯示:

  • ID
  • 比賽日期
  • team1_id
  • team2_id
  • team1 在過去 5 場比賽中的得分(3 - 獲勝,1 - 平局,0 - 負)
  • team2 在前 5 場比賽中的得分
  • 球隊2前5場比賽得分(客場)
  • 球隊2在前5場比賽中的積分,當它是球隊1時(主場比賽)

我嘗試為 team1 和 team2 添加帶有點的列,但我無法弄清楚如何使用視窗函式來總結正確的匹配點。

前 5 場比賽可以使用執行總數輕鬆計算:

select id, team_1_id, team2_id, match_date,
      sum(case 
            when score_team1 = score_team2 then 1
            when score_team1 > score_team2 then 3
            else 0
          end) over (order by match_date rows between 4 preceding and current rows) as prev_score_team1,
      sum(case 
            when score_team2 = score_team1 then 1
            when score_team2 > score_team1 then 3
            else 0
          end) over (order by match_date rows between 4 preceding and current rows) as prev_score_team2
from game
order by match_date;

“前 5 場比賽”的定義有點不清楚 - 是否包括“目前比賽”(這是上面的查詢所做的)還是不包括顯示總和的行?如果它應該排除您需要的目前行rows between 5 rows preceding and 1 preceding

我也不清楚“客隊”是如何辨識的,但是如果您將客隊的 id 儲存在列中(或類似的東西),那麼您可以使用filter()視窗函式的條件:

sum(case ... as above ... end) filter (where team_id = team1_id) over (... as above ..)

引用自:https://dba.stackexchange.com/questions/275011