【问题标题】:How to count data based on specific condition in OracleOracle中如何根据特定条件统计数据
【发布时间】:2021-10-20 22:30:48
【问题描述】:

假设我有一个人的表,其 id 和名称如下

[Person]
ID       NAME
================
1        Michael
2        Michelle
3        Emma
4        Evan
5        Ellen
6        Gary

我想根据他们名字的第一个字符来计算人数。 这是我期望的输出

NUMBER_OF_PERSONS
=================
2 //M = Michael and Michelle
3 //E = Emma, Evan and Ellen
1 //G = Gary

如何在 Oracle 中实现这一点?

这是我的查询

select count(id) as number_of_person    
from person
where substr(name) in (select distinct substr(name,1,1) from person); 

【问题讨论】:

    标签: sql oracle select count


    【解决方案1】:

    您可以使用以下解决方案实现该目的。

    with Person (ID, NAME ) as (
    select 1, 'Michael'  from dual union all
    select 2, 'Michelle' from dual union all
    select 3, 'Emma'   from dual union all
    select 4, 'Evan'   from dual union all
    select 5, 'Ellen'  from dual union all
    select 6, 'Gary' from dual
    )
    select count(*) || ' //' || substr(NAME, 1, 1) || ' = ' || 
      case 
        when regexp_count( listagg(NAME, ' and ') within group ( order by ID ), ' and ') > 1 
          then regexp_replace( listagg(NAME, ', ') within group ( order by ID ), ', ([^,]+)$', ' and \1 ', 1, 1 ) 
        else listagg(NAME, ' and ') within group ( order by ID )
      end  NUMBER_OF_PERSONS
    from Person
    group by substr(NAME, 1, 1)
    order by substr(NAME, 1, 1)
    ;
    

    db<>fiddle

    【讨论】:

    • 谢谢你的回答,很抱歉回复晚了@MDO
    【解决方案2】:

    如果你只想要计数,你可以使用group by:

    select substr(name, 1, 1) as first_letter,
           count(*) as number_of_person    
    from person
    group by substr(name, 1, 1) ;
    

    此外,如果您确实想要名称列表,则可以将其放在另一列中,假设没有太多:

    select substr(name, 1, 1) as first_letter,
           count(*) as number_of_person,
           listagg(name, ', ') within group (order by name) as names  
    from person
    group by substr(name, 1, 1) ;
    

    【讨论】:

    • 感谢您的回答,我认为您的解决方案可能有效 :) @Gordon Linoff
    【解决方案3】:

    这是我的解决方案:

    WITH tbl AS (
    SELECT 1 AS ID, 'Michael' AS NAME  FROM dual UNION
    SELECT 2, 'Michelle' FROM dual UNION
    SELECT 3, 'Emma'     FROM dual UNION
    SELECT 4, 'Evan'     FROM dual UNION
    SELECT 5, 'Ellen'    FROM dual UNION
    SELECT 6, 'Gary'     FROM dual
    )
    
    SELECT COUNT(1)
         , SUBSTR(names.name,1,1)
         , REGEXP_REPLACE((listagg(names.name,', ') WITHIN GROUP (ORDER BY names.name)), ',([^,]*)$', ' and \1')
      FROM tbl names
     GROUP BY SUBSTR(names.name,1,1);
    

    【讨论】:

    • 谢谢你的回答,我会调查一下@Gnqz
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 2021-06-21
    • 1970-01-01
    • 2016-08-06
    • 2021-05-02
    • 2023-02-16
    • 2020-11-13
    相关资源
    最近更新 更多