Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using COUNT in GROUP_CONCAT

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?

like image 500
mesnicka Avatar asked Jul 04 '13 06:07

mesnicka


People also ask

Is there a length limit to Group_concat?

I'm using GROUP_CONCAT() in a MySQL query to convert multiple rows into a single string. However, the maximum length of the result of this function is 1024 characters.

What is the difference between concat and Group_concat in MySQL?

The difference here is while CONCAT is used to combine values across columns, GROUP_CONCAT gives you the capability to combine values across rows. It's also important to note that both GROUP_CONCAT and CONCAT can be combined to return desired results.

What does Group_concat do in SQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.


2 Answers

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.

like image 181
peterm Avatar answered Oct 14 '22 14:10

peterm


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
like image 25
Inc33 Avatar answered Oct 14 '22 16:10

Inc33