MySQL get a summary of data based on part of a string
I have a ta开发者_运维问答ble of user information, from which I want to get a report listing the most common domains. I know that I need to use count and group by, but I'm not sure how to group by only part of a string, from the '@' symbol on. Any advice?
id email name etc..
---------------------------------------------
1 username@domain.com User Userson blah
SUBSTRING_INDEX might be useful here:
select
substring_index(email,'@',-1) as domain
,count(*) as userCount
from your_table
group by domain
order by usercount desc;
Try this method, using LOCATE()
and SUBSTRING()
SELECT
SUBSTRING(email FROM LOCATE('@', email)) AS domain
COUNT(*) AS numusers
FROM tbl
GROUP BY domain
ORDER BY numusers DESC
The above will list domains as @example.com
. To strip off the @
use instead:
SUBSTRING(email FROM LOCATE('@', email)+1) AS domain
精彩评论