Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

database - Oracle SQL count and group by

I am trying to show the details of movie, with number of roles and the number of genres it is classified as. (Family, Fantasy).

I expected the result to come out as:

movie_id   title              genre     count(movie_role) count(genre)  
675        harry potter a     family    3                 2
675        harry potter a     fantasy   3                 2
767        harry potter b     family    3                 1

My code:

SELECT movie_id, title, count(movie_role), genre
from moviesInGenre
group by movie_id, title, genre;

Because harry potter a is classified as genre family and fantasy, so I want it to have a column counting the genres it is classified as. (2). And harry potter b is classified as family only so should have a count of 1.

Sample data:

movie_id  title           movie_role   actor_id   aname   genre
675       harry potter a  Harry        10993      Jarney  Family
675       harry potter a  Nana         10232      Sam     Fantasy
767       harry potter b  John         10911      Cart    Family

Thanks in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do this with the help of subqueries which find the various distinct counts:

SELECT
    t.movie_id,
    t.title,
    t.genre,
    rc.role_cnt,
    g.genre_cnt
FROM moviesInGenre t
INNER JOIN
(
    SELECT movie_id, COUNT(DISTINCT movie_role) AS role_cnt
    FROM moviesInGenre
    GROUP BY movie_id
) rc
    ON rc.movie_id = t.movie_id
INNER JOIN
(
    SELECT movie_id, COUNT(DISTINCT genre) AS genre_cnt
    FROM moviesInGenre
    GROUP BY movie_id
) g
    ON g.movie_id = t.movie_id;

screen capture from demo link below

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...