Skip to content
Advertisement

SQL Server CASE expression that does not result in waterfall

If I have a case expression is there a way it does not work as a waterfall?

For example if I have the following dataset:

group    value
---------------
derek    5
cait     1
david    2
denver   3

Is there a way I can show the following results

CASE 
    WHEN group like 'd%' then d
    WHEN group like 'de% then de
    ELSE other

To show

group  value
--------------
d      10
de     8
other  3

Right now it shows as

group  value
--------------
d      10
other  2

Advertisement

Answer

You can use a left join instead:

select coalesce(which, 'other'), sum(t.value)
from t left join
     (values ('d%', 'd'), ('de%', 'de')
     ) v(pattern, which)
     on t.group like v.pattern
group by which;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement