How to group by with a special condition How to group by with a special condition sql sql

How to group by with a special condition


@bfavaretto is nice (+1 to him), but if you don't know about username prefix or they are different you can go with something like:

GROUP BY CASE             WHEN REGEXP_LIKE(username, '^\d+$') THEN 'GRP_OTHERS'                                                 ELSE username         END


Not very efficient, but should work:

SELECT     CASE WHEN username LIKE 'GRP%' THEN username ELSE 'GRP_OTHERS' END AS username,     COUNT(*)FROM hostWHERE seq BETWEEN 0 AND 2000GROUP BY CASE WHEN username LIKE 'GRP%' THEN username ELSE 'GRP_OTHERS' END;


If you wanted to do it by putting small groups into one bucket, instead of by a particular name pattern, you could use:

select (case when cnt > 100 then username else 'OTHER' end), sum(cnt) as cntfrom (select username, count(*) as cnt      from host      where seq between 0 and 2000      group by username     ) tgroup by (case when cnt > 100 then username else 'OTHER' end)