Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group by with a special condition

Currently when I issue this SQL, it gets the distinct username.

I have some distinct usernames, which represent groups, e.g. GRP_BSN.

I would like to group all the other usernames (which happens to be numeric) into a group e.g. GRP_OTHERS

select username, count(*)
from host
where seq between 0 and 2000
group by username;

63149   1
63732   1
64110   2
70987   12
76841   4
GRP_BSN 226
GRP_ASN 243
GRP_DSC 93

Can I achieve something like this:

GRP_OTHERS 20
GRP_BSN 226
GRP_ASN 243
GRP_DSC 93

EDIT: Modified query from answer

select username, count(*)
from host
  where created_dt 
  -- date selection
  between to_date('2012-may-23 00:00:00', 'yyyy-mon-dd hh24:mi:ss') 
  and to_date('2012-may-23 23:59:59', 'yyyy-mon-dd hh24:mi:ss')
GROUP BY CASE
             WHEN REGEXP_LIKE(username, '^\d+$') THEN 'GRP_OTHERS'
                                                 ELSE username
         END;
like image 447
Oh Chin Boon Avatar asked May 26 '12 01:05

Oh Chin Boon


1 Answers

@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
like image 134
zerkms Avatar answered Sep 20 '22 10:09

zerkms