SQL计数正则表达式匹配(PostgreSQL)

时间:2015-08-24 12:18:53

标签: sql regex postgresql count

我想从表中计算正则表达式实例。例如:

    message                    state
    ================================
    [foo] aaaa                 active
    [bar] aaaa                 idle
    [foo] bbbb                 idle
    [foo] cccc                 active
    [bar] dddd                 active
    [tar] eeee                 idle

我想要的是:

    messageType               ocurrences
    ====================================
    [foo]                             3
    [bar]                             2
    [tar]                             1

有没有办法做到这一点? 任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

如果您只想计算第一个"字"在邮件中,然后使用substring_index()

select substring_index(message, ' ', 1) as messageType, count(*)
from table t
group by substring_index(message, ' ', 1)
order by count(*) desc;

编辑:

您可以通过查找第一个空格在Postgres中执行此操作:

select left(message, position(' ' in message) as messageType, count(*)
from table t
group by messageType
order by count(*) desc;