2016-06-11 2 views
0

두 개의 테이블 "성냥"과 "상대"가 있습니다.postgresql에서 승리, 동점 및 분실 게임 계산

일치

id | date 
---+------------ 
1 | 2016-03-21 21:00:00 
2 | 2016-03-22 09:00:00 
... 

반대 (연주하지 않을 경우 점수가 null는)

id | match_id | team_id | score 
---+----------+---------+------------ 
1 | 1  | 1  | 0 
2 | 1  | 2  | 1 
3 | 2  | 3  | 1 
4 | 2  | 4  | 1 
4 | 3  | 1  | 
4 | 3  | 2  | 
.... 

목표는 다음 표를

Team | won | tie | lost | total 
-----+-----+-----+------+---------- 
2 | 1 | 0 | 0 | 1 
3 | 0 | 1 | 0 | 1 
4 | 0 | 1 | 0 | 1 
1 | 0 | 0 | 1 | 1 

포스트 그레스 V9.5

를 만드는 것입니다

어떻게해야합니까? (. 임 열린 어쩌면 말이 있다면 내 모델에서 다른 곳으로 "점수"이동하는)

답변

0

나누기 등 impera 내 아들

with teams as (
    select distinct team_id from opponents 
), 
teamgames as (
    select t.team_id, o.match_id, o.score as team_score, oo.score as opponent_score 
    from teams t 
    join opponents o on t.team_id = o.team_id 
    join opponents oo on (oo.match_id = o.match_id and oo.id != o.id) 
), 
rankgames as (
    select 
     team_id, 
     case 
      when team_score > opponent_score then 1 
      else 0 
     end as win, 
     case 
      when team_score = opponent_score then 1 
      else 0 
     end as tie, 
     case 
      when team_score < opponent_score then 1 
      else 0 
     end as loss 
    from teamgames 
), 
rank as (
    select 
     team_id, sum(win) as win, sum(tie) as tie, sum(loss) as loss, 
     sum(win * 3 + tie * 1) as score 
    from rankgames 
    group by team_id 
    order by score desc 
) 
select * from rank; 

: 당신은 아마 처음이 필요하지 않습니다 "와"당신은 아마 팀 당 하나 개의 레코드로 이미 테이블을 가지고

주 2 : 난 당신이 또한 하나 개의 쿼리와 동일한 결과를 얻을 수 있다고 생각하지만, 이런 식으로 단계는 명확하다

+0

Thansk @Jack, 트릭을합니다. 나는 LATERAL 조인 등으로 완전히 다른 방향으로 생각하고 있었다. – Marcus