10

目前,当我发出此 SQL 时,它会获得不同的用户名。

我有一些不同的用户名,它们代表组,例如GRP_BSN.

我想将所有其他用户名(恰好是数字)分组到一个组中,例如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

我可以实现这样的目标:

GRP_OTHERS 20
GRP_BSN 226
GRP_ASN 243
GRP_DSC 93

编辑:从答案修改查询

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;
4

3 回答 3

13

@bfavaretto 很好(对他+1),但是如果您不了解username前缀或者它们不同,您可以使用以下内容:

GROUP BY CASE
             WHEN REGEXP_LIKE(username, '^\d+$') THEN 'GRP_OTHERS'
                                                 ELSE username
         END
于 2012-05-26T01:54:58.727 回答
4

效率不高,但应该可以:

SELECT 
    CASE WHEN username LIKE 'GRP%' THEN username ELSE 'GRP_OTHERS' END AS username, 
    COUNT(*)
FROM host
WHERE seq BETWEEN 0 AND 2000
GROUP BY CASE WHEN username LIKE 'GRP%' THEN username ELSE 'GRP_OTHERS' END;
于 2012-05-26T01:53:35.637 回答
3

如果您想通过将小组放入一个存储桶中而不是通过特定的名称模式来做到这一点,您可以使用:

select (case when cnt > 100 then username else 'OTHER' end), sum(cnt) as cnt
from (select username, count(*) as cnt
      from host
      where seq between 0 and 2000
      group by username
     ) t
group by (case when cnt > 100 then username else 'OTHER' end)
于 2012-05-26T02:18:34.303 回答