1

When we have two tables with one to many relation how we can get the sum of left table column.

Ex:
Player (player_id,name)
Stats (player_id, game_id, score)

Player
1  Aaron Brooks
2  Beno Udrih
3  James harden

Stats
player_id  score year
1          5     2017
1          3     2017
2          4     2016

The result I need to get is (Player scores in 2017)
Player         Score
Aaron Brooks   8
Beno Udrih     0
James harden   0

One player have many stat records.
Then how can I get all the players list with his sum of total scores. (Even if stats not available for one player his score need to be 0)

Got the correct query

select p.player_id,p.name,coalesce(sum(s.score),0)
from player p
left join stats s on p.player_id = s.player_id and s.year=2017
group by p.player_id,p.name
Chythi
  • 13
  • 3

1 Answers1

0

Apply simple aggregation and use left join on stats table to get all the records from player table whether they have records associated in stats table or not

select p.player_id,p.name,coalesce(sum(s.score),0)
from player p
left join stats s on p.player_id = s.player_id
group by p.player_id,p.name

Demo

Edit for filter

Move your filter for stats table from where clause to on clause

select p.player_id,p.name,coalesce(sum(s.score),0)
from player p
left join stats s on p.player_id = s.player_id and s.year=2017
group by p.player_id,p.name

Applying filter on left table using where clause will convert from left join to inner join

Demo

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
  • Thank you @khalid, But when I filter it with year, it doesn't work correctly. Have you any idea why? select p.player_id,p.name,coalesce(sum(s.score),0) from player p left join stats s on p.player_id = s.player_id WHERE s.year=2017 group by p.player_id,p.name – Chythi Dec 29 '17 at 07:03
  • @Chythi Update your question how you are applying filter ? I suggest you to add filter after `on` like `and s.year = '2017'` – M Khalid Junaid Dec 29 '17 at 07:06
  • 1
    @Khalid, It works. Thank you great help! – Chythi Dec 29 '17 at 07:14