【问题标题】:GROUPING multiple LIKE string对多个 LIKE 字符串进行分组
【发布时间】:2020-07-15 10:16:26
【问题描述】:

数据:

2015478 warning occurred at 20201403021545
2020179 error occurred at 20201303021545
2025480 timeout occurred at 20201203021545
2025481 timeout occurred at 20201103021545
2020482 error occurred at 20201473021545
2020157 timeout occurred at 20201403781545
2020154 warning occurred at 20201407851545
2027845 warning occurred at 20201403458745

在上面的数据中,我感兴趣的字符串有warning、error和timeout这3种 我们可以有一个查询,它将按字符串分组并给出如下所示的出现次数

输出:

timeout 3
warning 3
error 2

我知道我可以编写单独的查询来单独查找计数。但对单个查询感兴趣 谢谢

【问题讨论】:

    标签: sql postgresql group-by sql-like


    【解决方案1】:

    您可以为此使用过滤聚合:

    select count(*) filter (where the_column like '%timeout%') as timeout_count, 
           count(*) filter (where the_column like '%error%') as error_count, 
           count(*) filter (where the_column like '%warning%') as warning_count
    from the_table;
    

    这将返回三列中的计数,而不是您指示的三行。

    如果您确实需要在单独的行中使用它,您可以使用regexp_replace() 来清理字符串,然后按此分组:

    select regexp_replace(the_column, '(.*)(warning|error|timeout)(.*)', '\2') as what,
           count(*) 
    from the_table
    group by what;
    

    【讨论】:

    • 谢谢 a_horse_with_no_name,第一个查询就是我需要的...完美的工作..非常感谢....
    【解决方案2】:

    请使用下面的查询,不要使用STRPOS对值进行硬编码

    select val, count(1) from
    (select substring(column_name ,position(' ' in (column_name))+1,
    length(column_name) - position(reverse(' ') in reverse(column_name)) - 
    position(' ' in (column_name))) as val from  matching) qry
    group by val;  -- Provide the proper column name
    

    演示:

    【讨论】:

    • 谢谢吉姆,但是由于某种原因我无法让它工作。非常感谢您在这里度过的时光
    • 为您提供了新的查询以及演示。让我知道它是否有帮助。试图在不对查询中的值进行硬编码的情况下帮助您
    【解决方案3】:

    如果您想在单独的行上进行此操作,您还可以使用横向连接:

    select which, count(*)
    from t cross join lateral
         (values (case when col like '%error%' then 'error' end),
                 (case when col like '%warning%' then 'warning' end),
                 (case when col like '%timeout%' then 'timeout' end)
         ) v(which)
    where which is not null
    group by which;
    

    另一方面,如果您只是想要第二个词——但不想硬编码值——那么你可以使用:

    select split_part(col, ' ', 2) as which, count(*)
    from t
    group by which;
    

    Here 是一个 dbfiddle。

    【讨论】:

    • 感谢 Gordon,但由于某种原因,我无法使其正常工作。非常感谢您在这里度过的时光
    • @SurajK 。 . .第二个查询按原样工作。第一个有错别字。我添加了一个 dbfiddle,表明两者都可以做你想做的事。
    猜你喜欢
    • 2012-01-27
    • 1970-01-01
    • 2022-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2012-03-11
    相关资源
    最近更新 更多