2

I have a table called MY_MOVIES with two columns: MOVIES and GENRES like this (the relationship is one movie to many genres):

GENRE         MOVIE
----------    --------------           
ACTION        MOVIE1
DRAMA         MOVIE1
CRIME         MOVIE2
DRAMA         MOVIE2
CRIME         MOVIE3
DRAMA         MOVIE3
ACTION        MOVIE4
ADVENTURE     MOVIE4
FANTASY       MOVIE4
ANIMATION     MOVIE5
ADVENTURE     MOVIE5
COMEDY        MOVIE5

This table have more than 100000 rows.

I'm trying to get an output like this:

MOVIES        GENRES
----------    -------------- 
MOVIE1        ACTION, DRAMA
MOVIE2        CRIME, DRAMA
MOVIE3        CRIME, DRAMA
MOVIE4        ACTION, ADVENTURE, FANTASY
MOVIE5        ANIMATION, ADVENTURE, COMEDY

I was trying with PIVOT like this (having the idea of replace 0 and 1 to genres later):

SELECT * FROM MY_MOVIES 
PIVOT (COUNT(MOVIE) FOR GENRE in (SELECT DISTINCT(GENRE) FROM MY_MOVIES) as MOVIE_GENRES

I have been thinking I'm doing it the wrong way.

APC
  • 144,005
  • 19
  • 170
  • 281

1 Answers1

9

Assuming that you are using Oracle (version 11gR2 or later):

select movies,
       listagg(genre, ', ') within group (order by genre) as genres
from my_movies
group by movies;
APC
  • 144,005
  • 19
  • 170
  • 281
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786