I want to get from this
+-----------+--------+---------+
| name | color | species |
+-----------+--------+---------+
| Tom | grey | cat |
| Jerry | brown | mouse |
| Sylvester | black | cat |
| Tweety | yellow | bird |
| Garfield | orange | cat |
| Odie | yellow | dog |
| Bugs | grey | rabbit |
| Daffy | black | duck |
+-----------+--------+---------+
to this
+---------+------+-------+-------+--------+--------+
| species | grey | brown | black | yellow | orange |
+---------+------+-------+-------+--------+--------+
| cat | 1 | 0 | 1 | 0 | 1 |
| mouse | 0 | 1 | 0 | 0 | 0 |
| bird | 0 | 0 | 0 | 1 | 0 |
| dog | 0 | 0 | 0 | 1 | 0 |
| rabbit | 1 | 0 | 0 | 0 | 0 |
| duck | 0 | 0 | 1 | 0 | 0 |
+---------+------+-------+-------+--------+--------+
in MySQL.
I know how to do it, if I know the colors in advance.
SELECT
species,
COUNT(DISTINCT if (color='grey', name, null)) AS 'grey',
COUNT(DISTINCT if (color='brown', name, null)) AS 'brown',
COUNT(DISTINCT if (color='black', name, null)) AS 'black',
[...]
FROM animals
GROUP BY species
Is there a way to achieve this without adding a new COUNT-block for every color that might occur? There would be a problem, if the name of the color could not be used as column name.
The easiest way in SQL is something like
SELECT
species, color, COUNT(name)
FROM animals
GROUP BY species, color
but that requires more code to transform the data on the client side.