Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select and group MySQL column by certain word in result

I have some data in a database (which I'm retrieving via PHP) like so:

+----------------------+
| Browser              |
+----------------------+
| Chrome 23.0.1271.97  |
| Chrome 24.0.1312.52  |
| Chrome 26.0.1410.64  |
| Chrome 25.0.1364.172 |
| Chrome 25.0.1364.152 |
| Safari 8536.25       |
| Internet Explorer 8.0|
| Mozilla 5.0          |
| Internet Explorer 7.0|

What I'd like to be able to do, if it's possible, is to SELECT, COUNT and GROUP BY the browser type, regardless of whether the version number differs so that the ideal output would be:

| Browser           | Count |
+-------------------+-------+
| Chrome            |   29  |
| Safari            |   15  |
| Internet Explorer |   45  |
| Mozilla           |   20  |

I've tried various searches for different SQL commands that I may have overlooked or not known about to see if the results can be got from the database without needing to do something with them in PHP afterwards to group and count the results, but so far all I can get is the different browsers grouped and counted by their version numbers.

If it isn't possible, which is the best way to go about doing this with MySQL/PHP?

like image 848
MrLewk Avatar asked Dec 26 '22 02:12

MrLewk


2 Answers

SELECT 
SUBSTRING_INDEX(browser,' ',1) as browser, 
count(SUBSTRING_INDEX(browser,' ',1)) as count 
FROM browsers
GROUP BY SUBSTRING_INDEX(browser,' ',1)
like image 181
ramazanulucay Avatar answered Dec 28 '22 21:12

ramazanulucay


This scirpt will work it is tested!

SELECT SUBSTRING_INDEX( Browser, ' ', 1 ) AS browser, count( id ) as count
FROM `table_name`
GROUP BY Browser
like image 38
webGautam Avatar answered Dec 28 '22 22:12

webGautam