简体   繁体   中英

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.

You can try the SQLFiddle here

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

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).

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".

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.

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.

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