[英]SQL count regex matches (PostgreSQL)
I would like to count the regex instances from a table. 我想从表中计算正则表达式实例。 For example:
例如:
message state ================================ [foo] aaaa active [bar] aaaa idle [foo] bbbb idle [foo] cccc active [bar] dddd active [tar] eeee idle
What I would like to have is following: 我想拥有的是:
messageType ocurrences ==================================== [foo] 3 [bar] 2 [tar] 1
Is there any way to do that? 有什么办法吗? Any help would be greatly appreciated!
任何帮助将不胜感激!
If you just want to count the first "word" in the message, then use substring_index()
: 如果您只想计算消息中的第一个“单词”,请使用
substring_index()
:
select substring_index(message, ' ', 1) as messageType, count(*)
from table t
group by substring_index(message, ' ', 1)
order by count(*) desc;
EDIT: 编辑:
You can do this in Postgres by looking for the first space: 您可以在Postgres中查找第一个空格来执行此操作:
select left(message, position(' ' in message) as messageType, count(*)
from table t
group by messageType
order by count(*) desc;
just like the response above but with Postgres version: 就像上面的响应一样,但带有Postgres版本:
select regexp_matches(message, '\[.+\]') as messageType, count (*) from table1 group by regexp_matches(message, '\[.+\]') order by count (*) desc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.