[英]Mysql Getting Results Group by SUM + a row with the sum of descarted rows
我在 mysql 中有以下問題:
從這樣的查詢:
select Category, count(*) as C
from categories_likes
group by Category
order by C desc
limit 3
我需要得到這樣的結果:
Category | C
Love | 10
Sad | 5
Angry | 3
Other | 50
其中 other 是“Other”行是結果中不需要但需要將所有類別分組到最后一行的其他類別中的計數總和。
希望有人可以幫助我。 謝謝
據推測,您希望將除“愛”、“悲傷”和“憤怒”之外的所有類別分組到一個名為“其他”的獨特組中。
如果是這樣,您可以使用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 個類別,然后是所有其他類別的總數,那么它有點不同。 Assming 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 個類別; 您可以根據需要增加子查詢的偏移量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.