I have a pretty simple table in a database with 3 columns called people
. Example:
user id notes
john 01 has red hair, last logged in 02/04/12
tony 02 has brown hair, last logged in 04/03/12
brian 03 has brown hair, last logged in 03/06/13
amanda 04 has blonde hair, last logged in 05/07/14
…
if I want to group by the notes field, and do a count, the 2nd and 3rd rows show as a count of 1 each because the logged in date is different; what I would like to do is chop off the date and amalgamate and count purely by hair colour, eg if I run a query:
SELECT `notes`, COUNT( `user` ) AS Count
FROM `people`
WHERE `notes` LIKE "%hair%" GROUP BY `notes`;
I get a result of:
+-----------------------------------------+-------+
|notes | Count |
+-----------------------------------------+-------+
|has red hair, last logged in 02/04/12 | 1|
|has brown hair, last logged in 04/03/12 | 1|
|has brown hair, last logged in 03/06/13 | 1|
|has blonde hair, last logged in 05/07/14 | 1|
+-----------------------------------------+-------+
would like to achieve a result of:
+-------------------+------+
|notes |Count |
+-------------------+------+
|has red hair | 1|
|has brown hair | 2|
|has blonde hair | 1|
+-------------------+------+
Is this at all possible?
Cheers.
You can do it using SUBSTRING_INDEX
, like this:
SELECT SUBSTRING_INDEX(`notes`, ',', 1), COUNT( `user` ) AS Count
FROM `people`
WHERE `notes` LIKE "%hair%"
GROUP BY SUBSTRING_INDEX(`notes`, ',', 1)
Of course this is a somewhat dirty workaround. A better approach would be to separate out the hair color, but I realize that this may not always be possible.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.