Using COUNT in GROUP_CONCAT Using COUNT in GROUP_CONCAT sql sql

Using COUNT in GROUP_CONCAT


You need to COUNT() with GROUP BY in an inner SELECT clause first and then apply GROUP_CONCAT();

SELECT GROUP_CONCAT(cnt) cntFROM (    SELECT COUNT(*) cnt    FROM table1    GROUP BY fk_company) q;

Output:

|   CNT   |-----------| 3,2,3,1 |

Here is SQLFiddle demo.


You can also achieve that by counting the number of commas (or whatever's your separator) in the GROUP_CONCAT:

SELECT (LENGTH(GROUP_CONCAT(DISTINCT fk_company))-LENGTH(REPLACE(GROUP_CONCAT(DISTINCT fk_company), ',', '')))FROM `table`GROUP BY fk_company


select GROUP_CONCAT(counts)    from (      select count(id) counts from          table group by fk_company   );