[英]How to use group by in this scenario with case expression?
我有电影和电影类型。 我正在显示电影类型,并显示该电影类型中存在的电影数量。 这可以通过对电影流派使用分组依据并计算电影ID来实现。
但是我不理解如何使用带有case语句的组来例如显示电影类型“喜剧”和“动作”的每个电影类型的计数,而不是显示每个电影类型的计数。其他流派显示“剩余”,然后显示不属于喜剧或动作的剩余电影的数量,例如:
Action 10
Comedy 7
Remaining 15
您知道达成此目标的必要条件吗? 因为即使电影类型不同于“喜剧”或“动作”,也必须始终按电影类型进行分组,但按电影类型进行分组也很有必要,但在这种情况下,需要显示这些电影的数量,而不是类型的“动作”和“喜剧”。
将派生表用于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!
您可以在下面尝试-
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
重复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;
另一种使用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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.