【问题标题】:Mysql Getting Results Group by SUM + a row with the sum of descarted rowsMysql通过SUM +一行与descarted行的总和获取结果组
【发布时间】:2020-03-14 20:22:20
【问题描述】:

我在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 是“其他”行是结果中不需要但需要在最后一行中分组的其他类别中的计数总和。

希望有人可以帮助我。 谢谢

【问题讨论】:

标签: mysql sql group-by count


【解决方案1】:

您大概想将除“爱”、“悲伤”和“愤怒”之外的所有类别归为一个独特的组,称为“其他”。

如果是这样,您可以使用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 个;您可以根据需要增加子查询的偏移量。

【讨论】:

  • Hello 将是第二个选项,动态 top3 和 Other 将合并所有其他类别,因此此选项仅在 Mysql 8 中? Mysql 5.7 呢?
  • @MoisesVega:我用早期版本的解决方案更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 2019-08-06
  • 1970-01-01
相关资源
最近更新 更多