Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group by with substring in MySQL

Tags:

mysql

group-by

I have a table called filestatistics:

id    file    userid    datetime
 1    p1          99    2017-04-15 09:05:10
 2    exp1        99    2017-04-15 09:25:17
 3    p2          99    2017-04-15 09:45:46
 4    exp2        99    2017-04-15 09:55:07

and I want to group and get the total entries per user them according to their filename but excluding the 'ex' string.

My query is:

SELECT file FROM filestatistics WHERE userid = 99 GROUP BY file;

My query above results in 4 entries which is wrong.

What would be the correct query to group the files per user?

Desired output is

2 files for userid = 99 
//since p1 and exp1 are grouped as 1
//since p2 and exp2 are grouped as 1
like image 448
Keith Leyson Avatar asked Apr 18 '17 07:04

Keith Leyson


People also ask

Can we use substring in Group by clause?

Yes I agree with you. But if substr(country,0,20) is same for 2 country , but the actual value of country is different, in that case, we can't display both country value in a group by output.

How do I select a part of a string in MySQL?

SUBSTRING() : function in MySQL is used to derive substring from any given string . It extracts a string with a specified length, starting from a given location in an input string. The purpose of substring is to return a specific portion of the string.

What is substring in MySQL?

Definition and Usage. The SUBSTRING() function extracts a substring from a string (starting at any position). Note: The SUBSTR() and MID() functions equals to the SUBSTRING() function.


1 Answers

You can use the following solution using REPLACE to get the files:

SELECT userid, REPLACE(file, 'ex', '') AS file, COUNT(id) AS cnt_files
FROM filestatistics 
GROUP BY REPLACE(file, 'ex', ''), userid

To get the COUNT of files of each user you can use the following:

SELECT COUNT(DISTINCT REPLACE(file, 'ex', '')) AS cnt_files
FROM filestatistics 
GROUP BY userid

demo on dbfiddle.uk

like image 198
Sebastian Brosch Avatar answered Sep 30 '22 05:09

Sebastian Brosch