简体   繁体   中英

How do I COUNT certain values as the same?

This query gives me the following result set:

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

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

I would like a query that sums the counts of certain values, like so:

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

One possibility that comes to mind is littering the whole query with duplicates of an ugly monstrosity of a CASE match, but I haven't tried it yet because I hate that kind of code duplication. Do better ways exist?

This should do the work

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;

You can replace the in ('blue', 'azure', 'sky-blue') part with a nested select from a table (or another source) that contain your blue definitions. But if it comes to that, then it will be better to just do a join

Eg

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

or if you don't have a table, but have a list of mappings and you want it "prettier"

; 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

Maybe the vendor you are using would allow you for a bit nicer syntax, especially in the union part.

PS Doesn't seem much better then the case when part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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