SQL group values for one column by another column

家住魔仙堡 提交于 2020-06-16 04:59:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!