简体   繁体   中英

How to use group by in this scenario with case expression?

I have movies and movie genres. I'm showing the movie genre and at right the number of movies that exist in that movie genre. This works using a group by on the movie genre and counting the movie ids.

However I'm not understanding how to use the group with the case statement to for example to show the count of each movie genre for the movie genres "Comedy" and "Action" for example but instead of show the count of each movie for the other genres show "Remain" and then the count of the remaining movies that don't belong to comedy or action, like:

Action  10
Comedy  7
Remaining  15

Do you know what is necessary to achieve this? Because is necessary to group always by the movie genre even when the movie genre is different from "Comedy" or "Action" is necessary to group by the movie genre, but in this case is necessary to show the count of these movies that are not of genre "Action" and "Comedy".

Use a derived table for the case expression . Then GROUP BY its result:

select genre, count(*)
from
(
    select case when genre in ('Action', 'Comedy') then genre
                else 'Remaining'
           end as genre
    from tablename
) dt
group by genre

ANSI SQL compliant!

You can try below -

select case when genres in ('Comedy','Action') then genres
else 'Remaining' end as genre,count(*) from tablename
group by case when genres in ('Comedy','Action') then genres
else 'Remaining' end

Repeat the case expression:

select (case when genre in ('Action', 'Comedy') then genre
             else 'Remaining'
        end) as new_genre,
       count(*)
from t
group by (case when genre in ('Action', 'Comedy') then genre
               else 'Remaining'
          end);

Some databases recognize column aliases in the group by , so this can sometimes be simplified to:

select (case when genre in ('Action', 'Comedy') then genre
             else 'Remaining'
        end) as new_genre,
       count(*)
from t
group by new_genre;

another way using Union ,

select genre,count(1) as cnt from tbl_movie where genre in ('Action','Comedy') group by genre
union
select 'others',count(1) as cnt from tbl_movie where genre not in  ('Action','Comedy')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM