You need to perform a PIVOT. In other databases, such as SQL Server, it is easier to do this. In Mysql you need to create aggregated expressions, as for example the one I created in Sql Fiddle, take a look around.
Basically, to the data universe below:
CREATE TABLE Turnos (`id` int, `turno` int);
INSERT INTO Turnos (`id`, `turno`)
VALUES
(1, 1),
(1, 1),
(1, 1),
(1, 2),
(1, 3),
(1, 5),
(1, 5),
(1, 6),
(1, 6),
(1, 7),
(1, 9),
(1, 9),
(1, 9)
;
We make the query as follows:
SELECT
SUM(CASE turno WHEN 1 THEN 1 ELSE 0 END) AS '1',
SUM(CASE turno WHEN 2 THEN 1 ELSE 0 END) AS '2',
SUM(CASE turno WHEN 3 THEN 1 ELSE 0 END) AS '3',
SUM(CASE turno WHEN 4 THEN 1 ELSE 0 END) AS '4',
SUM(CASE turno WHEN 5 THEN 1 ELSE 0 END) AS '5',
SUM(CASE turno WHEN 6 THEN 1 ELSE 0 END) AS '6',
SUM(CASE turno WHEN 7 THEN 1 ELSE 0 END) AS '7',
SUM(CASE turno WHEN 8 THEN 1 ELSE 0 END) AS '8',
SUM(CASE turno WHEN 9 THEN 1 ELSE 0 END) AS '9'
FROM Turnos
Reaching the desired result.
Tiago, I don’t think I expressed myself well at the time of creating this question... The value STRING '1,2,3,4,5,6,7,8,9' (in which never will be equal values, ie will be dynamic) originally being an ARRAY in PHP, is as input parameter in a Stored Procedure. From there, you would need to transform this ARRAY into TABLE, transposing it into a column, inserting from each element that is separated by comma individually. So that later, you can do the treatment on a CURSOR. So: Turn 1 2 3 4 5 6 7 8 9
– mcardoso