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?
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.
- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"
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.
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.
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
select
substring(substring_index(col1,'-',-1),1,3) as grp,
count(*) as total
from table
group by grp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With