首页 > 解决方案 > 如何将某些值计算为相同?

问题描述

此查询为我提供了以下结果集:

SELECT color, CCOUNT(color) FROM Table GROUP BY color;

color    | COUNT(color)
-----------------------
red      | 3
orange   | 1
blue     | 2
azure    | 2
sky-blue | 1

我想要一个汇总某些值的计数的查询,如下所示:

color                        | COUNT(color)
-------------------------------------------
red                          | 3
orange                       | 1
blues, just all of the blues | 5

想到的一种可能性是在整个查询中乱扔CASE匹配的丑陋怪物的重复,但我还没有尝试过,因为我讨厌这种代码重复。是否存在更好的方法?

标签: mysqlsqlcountmysql-5.7

解决方案


这应该做的工作

select 
  case 
    when color in ('blue', 'azure', 'sky-blue') then 'blues, just all of the blues'
    else color
  end as my_custom_color_naming,
  count(*)
from table
group by my_custom_color_naming;

您可以用in ('blue', 'azure', 'sky-blue')包含蓝色定义的表(或其他源)中的嵌套选择替换该部分。但是,如果涉及到这一点,那么最好只是加入

例如

select m.color_group, count(*)
from table t
join mappings m on t.color = m.color
group by m.color_group

或者如果您没有表格,但有一个映射列表并且您希望它“更漂亮”

; with mappings as (
  select 'blue', 'blues' as color_group
    union
  select 'azure', 'blues' as color_group 
    union
  select 'sky-blue', 'blues' as color_group
)
select m.color_group, count(*)
from table t
join mappings m on t.color = m.color
group by m.color_group

也许您使用的供应商会允许您使用更好的语法,尤其是在union部分中。

PS 似乎并没有比这case when部分好多少。


推荐阅读