[英]Returning SQL LIKE & GROUP BY results
I have a pretty simple table in a database with 3 columns called people
. 我在数据库中有一个非常简单的表,其中包含3列名为
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; 如果我想按注释字段分组并进行计数,则第2行和第3行显示为1,因为登录日期不同; 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: 您可以使用
SUBSTRING_INDEX
来执行此操作,如下所示:
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.
更好的方法是分离头发颜色,但我意识到这可能并不总是可行的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.