I need to calculate the best scorer(player_id
/ player_name
) per game_id
. As you can see below, I have three cases:
- Two or more guys have the same number of goals: in that case, we do not have any scorer.
- One guy is the only goal scorer.
- We have one scorer with clearly the highest score.
I have tried to make a query to give me the game_id
, player_name
, player_id
of the best scorer per game but without success. Here is my query:
select j.id as game_id,jg.id as player_id, jg.nome s player_name,
count(g.id) as numberOfGoals,
RANK() OVER(PARTITION BY j.id ORDER BY count(g.id) ) as rank
from jogo j
inner join jogo_jogador jj on jj.jogo_id = j.id
inner join golo g on g.jogo_jogador_id = jj.id
inner join equipa_jogador ej on ej.id = jj.equipa_jogador_id
inner join jogador jg on jg.id = ej.jogador_id
group by jg.id, jg.nome, j.id
order by j.id, jg.nome, jg.id;
This is what I currently get:
insert into tbl(game_id player_id player_name numberofgoals rank)
values
(1 , 1 ,'Marco Costa' ,1 ,1),
(1 , 4 ,'Olivier Marques',1 ,1),
(2 , 1 ,'Marco Costa' ,1 ,1),
(3 , 9 ,'Ilidio Vatuva' ,2 ,2),
(3 ,10 ,'Joaquim Barros' ,1 ,1),
(4 ,11 ,'Diogo Mendonça' ,2 ,4),
(4 ,10 ,'Joaquim Barros' ,1 ,1),
(4 ,14 ,'John Smith' ,1 ,1),
(4 ,12 ,'Mário Jorge' ,1 ,1),
(5 , 7 ,'Ricardo Pereira',1 ,1),
(6 , 8 ,'Danilo Barbosa' ,1 ,1),
(6 , 9 ,'Ilidio Vatuva' ,1 ,1),
(6 ,19 ,'Micael Pereira' ,1 ,1),
(6 ,18 ,'Ricardo Bateiro',2 ,4),
(7 , 8 ,'Danilo Barbosa' ,3 ,1),
(9 , 8 ,'Danilo Barbosa' ,1 ,1),
(9 , 2 ,'Joao Azevedo' ,1 ,1),
(9 , 7 ,'Ricardo Pereira',1 ,1),
(10, 9 ,'Ilidio Vatuva' ,1 ,1),
(11, 3 ,'Kevin Soares' ,1 ,1),
(11, 1 ,'Marco Costa' ,1 ,1),
(11,18 ,'Ricardo Bateiro',2 ,3),
(12,21 ,'Daniel Silva' ,1 ,1),
(12, 9 ,'Ilidio Vatuva' ,1 ,1),
(13, 2 ,'Joao Azevedo' ,1 ,1);
I am working with PostgreSQL 13.2.
For game_id 1 (as example):