问题
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;
回答1:
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.
回答2:
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;
STRING_AGG()
Live Demo
来源:https://stackoverflow.com/questions/46555675/sql-group-values-for-one-column-by-another-column