SQL计数正则表达式匹配(PostgreSQL)
我想从表中计算regex实例。例如: message state ================================ [foo] aaaa active [bar] aaaa idle [foo] bbbb idle [foo] cccc active [bar] dddd active [tar] eeee idle 消息状态 ================================ [foo]aaaa激活 [bar]aaaa空闲 [foo]bbbb空闲 [foo]中交建投活跃 [bar]dddd处于活动状态 [tar]eeee空闲 我想要的是: messageType ocurrences ==================================== [foo] 3 [bar] 2 [tar] 1 消息型眼病 ==================================== [foo]3 [酒吧]2 [tar]1 有办法吗?SQL计数正则表达式匹配(PostgreSQL),sql,regex,postgresql,count,Sql,Regex,Postgresql,Count,我想从表中计算regex实例。例如: message state ================================ [foo] aaaa active [bar] aaaa idle [foo] bbbb idle [foo] cccc active [bar] ddd
任何帮助都将不胜感激 如果您只想计算消息中的第一个“单词”,请使用
子字符串\u index()
:
编辑:
您可以在Postgres中查找第一个空格:
select left(message, position(' ' in message) as messageType, count(*)
from table t
group by messageType
order by count(*) desc;
与上面的回答一样,但使用Postgres版本: select regexp_matches(message, '\[.+\]') as messageType, count (*) from table1 group by regexp_matches(message, '\[.+\]') order by count (*) desc; 选择regexp\u匹配项(消息“\[.+\]”)作为消息类型,计数(*) 来自表1 按regexp\u匹配项分组(消息“\[.+\]”) 按计数排序(*)说明;
什么是“regex实例”?我是说更多的regex“匹配”。谢谢怎么样?谢谢你的回复!我认为这是一个很好的提示,但我忘了提到,我的数据库是PostgreSQL,不支持子字符串索引。 select regexp_matches(message, '\[.+\]') as messageType, count (*) from table1 group by regexp_matches(message, '\[.+\]') order by count (*) desc;