Using COUNT in GROUP_CONCAT
Asked Answered
M

4

17

This is my table:

  id  | fk_company
-------------------
  1   |     2    
  2   |     2    
  3   |     2    
  4   |     4    
  5   |     4    
  6   |     11   
  7   |     11   
  8   |     11   
  9   |     12

The result I want should be string "3, 2, 3, 1" (count of items that belong to each company), because this is just part of my complex query string.

I tried to use this query:

SELECT GROUP_CONCAT(COUNT(id) SEPARATOR ", ")
FROM `table` GROUP BY fk_company;

But I got an error:

Error Number: 1111
Invalid use of group function

I have a feeling COUNT, MAX, MIN or SUM can't be used in GROUP_CONCAT. If so, do you know another way to do this?

Marcille answered 4/7, 2013 at 6:21 Comment(1)
Why do you want this? What happens next?Peraza
Q
22

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

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

Output:

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

Here is SQLFiddle demo.

Questor answered 4/7, 2013 at 6:27 Comment(2)
Thank you very much, I spent a lot of time to fix this. Unfortunately I don't have enough time to play so I needed help even if this result looks so easy.Marcille
Note that this presently relies on the fact that fk_company numbers are arranged sequentially, in a manner that corresponds to idPeraza
R
3

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
Rakia answered 8/8, 2020 at 5:9 Comment(0)
U
0
select GROUP_CONCAT(counts) 
   from (
      select count(id) counts from
          table group by fk_company
   );
Uranometry answered 4/7, 2013 at 6:26 Comment(0)
W
-1
SELECT A,  
GROUP_CONCAT(B SEPARATOR '/') AS 'Category',  
GROUP_CONCAT(C SEPARATOR '/') AS 'ALIAS_NAME',COUNT('ALIAS_NAME') AS 'Count'  
FROM carnews  
...  
...
GROUP BY 1
ORDER BY 4 DESC  

This works well in my case.

Winsome answered 16/10, 2018 at 7:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.