Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL GROUP by Regex?

I have the following query

SELECT Count(*) as Total_Count, Col1 
FROM Table1 
GROUP BY Col1 
ORDER BY Total_Count DESC;

I want to zoom in on Col1. The data in Col1 are in the following format:

text-abc1
txt4-abcde22
tex6-abc2
text4-imp4
text-efg1
txt-efg43

I want to be able to group it by

After the first `-`, any first three/four/five characters match

In this example, if we match with first 3 characters. Output will be:

Total_Count   Col1
3             abc
1             imp
2             efg

Any other way to achieve this?

like image 482
theking963 Avatar asked Nov 25 '11 19:11

theking963


People also ask

Can I use regex in MySQL?

MySQL supports another type of pattern matching operation based on the regular expressions and the REGEXP operator. It provide a powerful and flexible pattern match that can help us implement power search utilities for our database systems.

Why * is used in regex?

- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"

How do I sort last 3 characters in SQL?

SELECT *FROM yourTableName ORDER BY RIGHT(yourColumnName,3) yourSortingOrder; Just replace the 'yourSortingOrder' to ASC or DESC to set the ascending or descending order respectively. Here is the query to order by last 3 chars. Case 1 − Get the result in ascending order.

How do I match a string in MySQL?

STRCMP() function in MySQL is used to compare two strings. If both of the strings are same then it returns 0, if the first argument is smaller than the second according to the defined order it returns -1 and it returns 1 when the second one is smaller the first one.


2 Answers

You might not need a regex, just string operations. For three characters:

SELECT count(*) AS Total_Count,
SUBSTRING(Col1 FROM POSITION('-' in Col1)+1 FOR 3) AS Col1_zoomed
FROM Table1
GROUP BY Col1_zoomed
ORDER BY Total_Count DESC
like image 170
Ian Clelland Avatar answered Oct 14 '22 02:10

Ian Clelland


select
substring(substring_index(col1,'-',-1),1,3) as grp,
count(*) as total
from table
group by grp
like image 42
Nicola Cossu Avatar answered Oct 14 '22 03:10

Nicola Cossu