我想计算一个人有多少动物,并计算每只动物的个体数。我有一个包含此类列的表
| name | animals |
-------------------------
| abc | 'dog' |
| def | 'dog' |
| def | 'cat' |
| abc | 'dog' |
| def | 'cat' |
| def | 'mouse' |
| abc | 'cat' |
| def | 'dog' |
我的结果应该是这样的
| name | dog | cat | mouse | Total |
--------------------------------------------------------
| abc | 2 | 1 | 0 | 3 |
| def | 2 | 2 | 1 | 5 |
有人可以告诉我如何查询?
答案 0 :(得分:1)
SELECT *,
(dogs + cats + mouses) as total
FROM(
SELECT
tdogs.name,
IFNULL(ndogs,0) as dogs,
IFNULL(ncats,0) as cats,
IFNULL(nmouses,0) as mouses
FROM (SELECT name, count(*) ndogs FROM mytable where animals='dog' GROUP BY name) tdogs
LEFT JOIN
(SELECT name, count(*) ncats FROM mytable where animals='cat' GROUP BY name) tcats
ON tdogs.name = tcats.name
LEFT JOIN
(SELECT name, count(*) nmouses FROM mytable where animals='mouse' GROUP BY name ) tmouses
ON tmouses.name=tcats.name
GROUP BY tdogs.name) x
我遇到了一个错误,因为我在计算鼠标时得到NULL
,但我已经修复了,这就像你想要的那样。
您可以尝试SQLFiddle here
答案 1 :(得分:0)
您可以尝试类似
的内容SELECT name, animals, COUNT(1)
FROM table
GROUP BY name, animals
通过这种方式,您将获得与您所要求的格式不同的格式的结果,但数据是......计算您可以使用php的总数
答案 2 :(得分:0)
修改强> - 如评论中所述,这种方式不有效。更简单的方法是使用SQL过程或过程语言(例如PHP)来完成此操作。
你可以制作一些子查询来处理这个,但我认为你不能完全动态地管理它。我假设你的表名为“my_table”。
SELECT
t.name,
(SELECT COUNT(*) FROM my_table t2 WHERE t2.name = t.name AND t2.animals = 'dog' ) AS 'dog',
(SELECT COUNT(*) FROM my_table t3 WHERE t3.name = t.name AND t3.animals = 'cat' ) AS 'cat',
(SELECT COUNT(*) FROM my_table t4 WHERE t4.name = t.name AND t4.animals = 'mouse' ) AS 'mouse'
FROM
my_table t
GROUP BY t.name;
我没有测试这个查询,这是为了说明这个想法。