Using COUNT in GROUP_CONCAT

2020-07-03 07:41发布

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" 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.

3条回答
Summer. ? 凉城
2楼-- · 2020-07-03 08:03
select GROUP_CONCAT(counts) 
   from (
      select count(id) counts from
          table group by fk_company
   );
查看更多
孤傲高冷的网名
3楼-- · 2020-07-03 08:05

You need to COUNT() with GROUP BY in an inner select 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

查看更多
Juvenile、少年°
4楼-- · 2020-07-03 08:11
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.

查看更多
登录 后发表回答