Question Details

No question body available.

Tags

sql oracle-database

Answers (3)

Accepted Answer Available
Accepted Answer
May 27, 2026 Score: 5 Rep: 526,813 Quality: High Completeness: 50%

You should aggregate by precisely the same CASE expression which appears in the select clause:

SELECT
    CASE
        WHEN animal IN ('chicken', 'crow') THEN 'bird'
        WHEN animal in ('dog', 'cat') THEN 'mammal'
    END AS animal,
    SUM(legs) AS legs
FROM t1
WHERE
    animal IN ('chicken', 'crow', 'dog', 'cat')
GROUP BY
    CASE
        WHEN animal IN ('chicken', 'crow') THEN 'bird'
        WHEN animal in ('dog', 'cat') THEN 'mammal'
    END;

Note also that the ELSE condition you currently have does not make sense, so I have removed it.

May 28, 2026 Score: 2 Rep: 8,809 Quality: Low Completeness: 80%

Perhaps you already have a list of categories in the form of a table or defined in some other way.
Can be used explicitly

SELECT c.category,sum(legs) as legs 
FROM test t
INNER JOIN ( 
    VALUES 
           ('chicken','bird')
          ,('crow','bird')
          ,('dog','mammal')
          ,('cat','mammal')
   )c(animal,category) ON c.animal=t.animal
GROUP BY c.category
;

There
IN(...) -> "INNER JOIN"
CASE ... END -> c.category

Let's say you have an "animalcategory" table or query

create table animalcategory (animal varchar(15),category varchar(15));
-- and possible
create index ixanimalcategoryanimal on animalcategory(animal);
create index ixanimalanimal on animal(animal);

Then

SELECT c.category,sum(legs) as legs 
FROM animal t
INNER JOIN animal_category c ON c.animal=t.animal
WHERE category IN('bird','mammal')
GROUP BY c.category
;

This approach will be much more productive on big data than using the CASE...END. It will be possible to use indexes.

Fiddle

May 28, 2026 Score: 0 Rep: 182,889 Quality: Low Completeness: 40%

Oracle 23.9 and newer supports GROUP BY ALL:

SELECT CASE WHEN animal IN ('chicken', 'crow') THEN 'bird' WHEN animal IN ('dog', 'cat') THEN 'mammal' ELSE animal END AS animal, SUM(legs) AS legs FROM t1 WHERE animal IN ('chicken', 'crow', 'dog', 'cat') GROUP BY ALL;