Is there some kind of "aggregate" function in SQL that just turns values into a list? An example might be a table of the form:
| game_id | player | score |
|---------|--------|-------|
| 1 | fred | 2 |
| 1 | tom | 1 |
| 2 | fred | 3 |
| 2 | tom | 4 |
What I would like returned is a table that looks like this:
| player | scores |
|--------|--------|
| fred | 2, 3 |
| tom | 1, 4 |
The command might look something like: SELECT player, listify(score) FROM games GROUP BY player;
Thanks to Tim and Gordon. The Postgres function I'm looking for is array_agg
. The full query in this case looks like this:
SELECT player, array_to_string(array_agg(score), ',') AS scores FROM games GROUP BY player;
array_agg
puts all the scores into an array, and you have to convert them to a string to be able to return them in a SELECT statement.
You can use string_agg
so then you'll not need to call 2 different functions array_agg
and array_to_string
.
SELECT player, string_agg(score::text, ',') AS scores FROM games GROUP BY player;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.