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
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.
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.
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.
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
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