我在数据库中有一个非常简单的表,其中有3列名为people
。例如:
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
…
如果我想按注释字段分组并进行计数,则第2行和第3行显示为1的计数,因为登录日期不同;我想做的是砍掉日期并合并并完全按头发颜色计算,例如如果我运行查询:
SELECT `notes`, COUNT( `user` ) AS Count
FROM `people`
WHERE `notes` LIKE "%hair%" GROUP BY `notes`;
我得到的结果是:
+-----------------------------------------+-------+
|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|
+-----------------------------------------+-------+
希望实现以下结果:
+-------------------+------+
|notes |Count |
+-------------------+------+
|has red hair | 1|
|has brown hair | 2|
|has blonde hair | 1|
+-------------------+------+
这一切都可能吗?
干杯。
答案 0 :(得分:3)
您可以使用SUBSTRING_INDEX
执行此操作,如下所示:
SELECT SUBSTRING_INDEX(`notes`, ',', 1), COUNT( `user` ) AS Count
FROM `people`
WHERE `notes` LIKE "%hair%"
GROUP BY SUBSTRING_INDEX(`notes`, ',', 1)
当然这是一个有点脏的解决方法。更好的方法是分离头发颜色,但我意识到这可能并不总是可能。