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

标签 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

有什么办法吗? 任何帮助将不胜感激!

最佳答案

如果你只想计算消息中的第一个“单词”,那么使用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;

关于SQL 计数正则表达式匹配 (PostgreSQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32182160/

相关文章:

SQL - Concat 全名,只有在姓氏存在时才包含空格

python - 如何删除引用某个对象的所有嵌套对象?

python - 如何将不相关模型的查询集序列化为嵌套序列化程序?

mysql - 检索 User_ID 在 12 月而非 1 月进行交易的记录

c# - 连字符前后的正则表达式模式匹配

c - C中的正则表达式,检查字符串是否包含特定字符

python正则表达式在<a>元素处拆分字符串并提取链接+文本

sql - 使用 max 查找最常出现的 column_name

对引用其他列的列进行 SQL 检查约束

php - 如果MySQL表中有多条相同的记录,如何只选择一条记录