Concatenate multiple result rows of one column into one, group by another column [duplicate]

∥☆過路亽.° 提交于 2019-11-26 04:07:28

问题


This question already has an answer here:

  • How to concatenate strings of a string field in a PostgreSQL 'group by' query? 14 answers

I\'m having a table like this

Movie   Actor   
  A       1
  A       2
  A       3
  B       4

I want to get the name of a movie and all actors in that movie, and I want the result to be in a format like this:

Movie   ActorList
 A       1, 2, 3

How can I do it?


回答1:


Simpler with the aggregate function string_agg() (Postgres 9.0 or later):

SELECT movie, string_agg(actor, ', ') AS actor_list
FROM   tbl
GROUP  BY 1;

The 1 in GROUP BY 1 is a positional reference and a shortcut for GROUP BY movie in this case.

string_agg() expects data type text as input. Other types need to be cast explicitly (actor::text) - unless an implicit cast to text is defined - which is the case for all other character types (varchar, character, "char"), and some other types.

As isapir commented, you can add an ORDER BY clause in the aggregate call to get a sorted list - should you need that. Like:

SELECT movie, string_agg(actor, ', ' ORDER BY actor) AS actor_list
FROM   tbl
GROUP  BY 1;

But it's typically faster to sort rows in a subquery. See:

  • Postgres SQL - Create Array in Select



回答2:


You can use array_agg function for that:

SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";

Result:

| MOVIE | ACTOR |
-----------------
|     A | 1,2,3 |
|     B |     4 |

See this SQLFiddle

For more See 9.18. Aggregate Functions




回答3:


 select movie,GROUP_CONCAT(DISTINCT Actor) as ActorList from toyr_table group by movie 

you can read it here http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php



来源:https://stackoverflow.com/questions/15847173/concatenate-multiple-result-rows-of-one-column-into-one-group-by-another-column

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