简体   繁体   English

在一行中按名称对列组的值进行计数

[英]count values of a column group by name in a single row

I want to count how many animals particular person has and count individual of each animal. 我想计算特定人有多少只动物,并计算每只动物的个体。 I have a table with such columns 我有一张桌子有这样的列

|   name   |   animals  |
-------------------------
|   abc    |    'dog'   |
|   def    |    'dog'   |
|   def    |    'cat'   |
|   abc    |    'dog'   |
|   def    |    'cat'   |
|   def    |    'mouse' |
|   abc    |    'cat'   |
|   def    |    'dog'   |

My result should be something like this 我的结果应该是这样的

|   name   |  dog    |   cat   |   mouse   |   Total   |
--------------------------------------------------------
|   abc    |   2     |    1    |     0     |     3     |
|   def    |   2     |    2    |     1     |     5     |

Please can someone tell me how can I make a query for that? 请有人能告诉我如何查询吗?

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

I had an error because when I get NULL when I count mouses, but I've fixed, this works like you want. 我有一个错误,因为当我计算鼠标数时当我为NULL时,但是我已经修复了问题,这就像您想要的那样。

You can try the SQLFiddle here 您可以在这里尝试SQLFiddle

You could try something like 您可以尝试类似

SELECT name, animals, COUNT(1)
FROM table
GROUP BY name, animals

In this way you will obtain the result in a format differend from the one you asked for, but the data are there... to compute the total you could then use php 这样,您将获得与您要求的格式不同的结果,但是数据在那里...计算总数,然后可以使用php

EDIT - As mentioned in comments, this way does not work. 编辑 -如评论中所述,这种方式不起作用 An easier manner could be to do this with a SQL procedure or with a procedural language (such as PHP). 一种更简单的方法是使用SQL过程或过程语言(例如PHP)来执行此操作。

You could make some subqueries to handle this, but I don't think that you could manage it entirely dynamically. 您可以进行一些子查询来处理此问题,但我认为您不能完全动态地对其进行管理。 I assume your table is named "my_table". 我假设您的表名为“ 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;

I did not test this query, this is to illustrate the idea. 我没有测试这个查询,这是为了说明这个想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM