如何在这种情况下使用group by表达式?

问题描述 投票:0回答:4

我有电影和电影类型。我正在展示电影类型,并且正确地显示了该电影类型中存在的电影数量。这适用于使用电影类型的分组和计算电影ID。

但是,我不理解如何使用带有case语句的组来例如显示电影类型“喜剧”和“动作”的每个电影类型的计数,而不是显示每个电影的计数其他类型显示“剩余”,然后是不属于喜剧或动作的剩余电影的数量,如:

Action  10
Comedy  7
Remaining  15

你知道实现这个目的有什么必要吗?因为即使电影类型不同于“喜剧”或者“动作”需要按照电影类型进行分组,因此必须始终按照电影类型进行分组,但是在这种情况下需要显示这些不是这些电影的数量流派“行动”和“喜剧”。

sql database
4个回答
1
投票

重复case表达式:

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);

有些数据库会识别group by中的列别名,因此有时可以将其简化为:

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

2
投票

使用派生表作为case表达式。然后GROUP BY的结果:

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兼容!


1
投票

你可以尝试下面 -

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

0
投票

使用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')
© www.soinside.com 2019 - 2024. All rights reserved.