Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

postgres aggregate results from joined table

Newbie Postgres question.

I have the following tables

players: id, name, …

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

votes: id, player_id, week – i.e. in votes there will be multiple records for each player_id

I want to get name (from players), vs: week[] (from votes where player_id == players.id)

i.e. I want to know which weeks each player voted in

select players.name, votes.week
  from public.votes
  join public.players
  ON votes.player_id = players.id

gets me the number of results in the votes in table, but that includes endless duplicates of name. I want 1 row per player, with the weeks in a list

Is that possible?

>Solution :

You could group by the players’ name and use array_agg to get an array of weeks:

SELECT   players.name, ARRAY_AGG(votes.week)
FROM     public.votes
JOIN     public.players ON votes.player_id = players.id
GROUP BY playes.name
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading