您大概想将除“爱”、“悲伤”和“愤怒”之外的所有类别归为一个独特的组,称为“其他”。
如果是这样,您可以使用case 表达式:
select
case
when category in ('Love', 'Sad', 'Angry') then category
else 'Other'
end new_category,
count(*) cnt
from categories_like
group by new_category
order by (new_category = 'Other'), cnt desc
请注意,查询的order by 子句将“其他”类别放在最后。
如果您想要动态的前 3 个类别,然后是所有其他类别的总数,那就有点不同了。假设 MySQL 8.0,可以使用排名函数:
select case when rn <= 3 then category else 'Other' end new_category, sum(cnt) cnt
from (
select category, count(*) cnt, rank() over(order by count(*) desc) rn
from categories_like
group by category
) t
group by new_category
order by (new_category = 'Other'), cnt desc
在早期版本中,我建议union all:
(
select category new_category, count(*) cnt
from categories_like
group by category
order by cnt desc
limit 3
)
union all (
select 'Other', sum(cnt)
from (
select category, count(*) cnt
from categories_like
group by category
order by cnt desc
limit 4, 1000
) t
)
order by (new_category = 'Other'), cnt desc
这里假设类别不超过 1000 个;您可以根据需要增加子查询的偏移量。