Question

If I have a view:

Movie             Genre    Actor
-------------------------------------------
Ocean's Twelve    Crime    George Clooney
Ocean's Twelve    Crime    Julia Roberts
Ocean's Twelve    Crime    Brad Pitt
Forrest Gump      Drama    Tom Hanks

How would I group by the movie title, but flatten the other columns like so:

Movie             Genre    Actor
-------------------------------------------
Ocean's Twelve    Crime    George Clooney, Julia Roberts, Brad Pitt
Forrest Gump      Drama    Tom Hanks

Note that if an element is equivalent, it is not repeated (e.g. Crime)

Was it helpful?

Solution

MySQL

Use GROUP_CONCAT() function:

SELECT movie, Genre, GROUP_CONCAT(Actor) AS Actor
FROM tableA
GROUP BY movie, Genre

SQL SERVER

SELECT A.movie, A.Genre, MAX(STUFF(B.ActorNames, 1, 1, '')) AS Actor
FROM tableA A 
CROSS APPLY(SELECT ' ' + Actor + ',' FROM tableA B 
            WHERE A.movie = B.movie AND A.Genre = B.Genre 
            FOR XML PATH('')
          ) AS B (ActorNames)
GROUP BY A.movie, A.Genre

OTHER TIPS

You are looking for GROUP_CONCAT

select Movie, Genre, group_concat(Actor separator ', ') as `Actors`
from
movies
group by Movie, Genre;

You need group_concat and group by http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat Try this

select Movie, Genre, group_concat(Actor) from view_name group by Movie
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top