-
Notifications
You must be signed in to change notification settings - Fork 0
/
20180116103553_create_standings_view.exs
99 lines (97 loc) · 3.7 KB
/
20180116103553_create_standings_view.exs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
defmodule SoSoSoccer.Crud.Repo.Migrations.CreateStandingsView do
use Ecto.Migration
def up do
execute("""
create view standings as
select t.season,
t.team_id,
max(te.long_name) as team_name,
max(t.league_id) as league_id,
sum(t.games)::int as games,
sum(t.wins)::int as wins,
sum(t.draws)::int as draws,
sum(t.losses)::int as losses,
sum(t.goals_for)::int as goals_for,
sum(t.goals_against)::int as goals_against,
(sum(t.goals_for) - sum(t.goals_against))::int as goal_difference,
sum(t.points)::int as points
from
(select home_team_api_id as team_id,
m.season,
max(m.league_id) as league_id,
count(m.home_team_api_id) as games,
sum(m.home_team_wins) as wins,
sum(m.home_team_draws) as draws,
sum(m.home_team_losses) as losses,
sum(m.home_team_goal) as goals_for,
sum(m.away_team_goal) as goals_against,
sum(m.home_team_points) as points
from
(select *,
case
when home_team_goal > away_team_goal then 3
when home_team_goal = away_team_goal then 1
else 0
end as home_team_points,
case
when home_team_goal > away_team_goal then 1
else 0
end as home_team_wins,
case
when home_team_goal = away_team_goal then 1
else 0
end as home_team_draws,
case
when home_team_goal < away_team_goal then 1
else 0
end as home_team_losses
from matches) m
join leagues l on m.league_id = l.id
group by season,
home_team_api_id
union all select away_team_api_id as team_id,
m.season,
max(m.league_id) as league_id,
count(m.away_team_api_id) as games,
sum(m.away_team_wins) as wins,
sum(m.away_team_draws) as draws,
sum(m.away_team_losses) as losses,
sum(m.away_team_goal) as goals_for,
sum(m.home_team_goal) as goals_against,
sum(m.away_team_points) as points
from
(select *,
case
when away_team_goal > home_team_goal then 3
when home_team_goal = away_team_goal then 1
else 0
end as away_team_points,
case
when away_team_goal > home_team_goal then 1
else 0
end as away_team_wins,
case
when away_team_goal = home_team_goal then 1
else 0
end as away_team_draws,
case
when away_team_goal < home_team_goal then 1
else 0
end as away_team_losses
from matches) m
join leagues l on m.league_id = l.id
group by season,
away_team_api_id) t
join leagues l on t.league_id = l.id
join teams te on te.api_id = t.team_id
group by (t.team_id,
t.season)
order by points desc,
goal_difference desc,
goals_for desc;
""")
end
def down do
execute("drop view standings;")
end
end