繁体   English   中英

如何将某些值计算为相同?

[英]How do I COUNT certain values as the same?

这个查询给了我以下结果集:

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 whencase when好多少。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM