mysql - 如何将某些值计算为相同?
问题描述
此查询为我提供了以下结果集:
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
匹配的丑陋怪物的重复,但我还没有尝试过,因为我讨厌这种代码重复。是否存在更好的方法?
解决方案
这应该做的工作
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
部分好多少。
推荐阅读
- javascript - 未处理的拒绝 (TypeError):fs.readdir 不是函数
- https - 为 insecure-requests=redirect 更改 quarkus 安全端口
- c# - 将 .ToArray() 放入 from/in 时,LINQ 查询性能不佳
- amazon-web-services - 是否可以使用“HTTP”协议(而不是 REST)通过 AWS API Gateway 返回 HTML?
- ffmpeg - 无法使用 ffmpeg 播放录制的视频和音频
- sql - 如何使用 Vertica 将 IPv6 中的地址转换为数字
- spring - 如何使用 spring-authorization-server 在 JWT 中创建自定义声明
- typescript - 手动传递 3 个泛型中的 1 个并告诉编译器推断其余的
- javascript - 在 React Router 中传递数据
- azure-devops - 用户无法在 Azure DevOps 的 sprint 上配置任务板设置