MySQL 在 GROUP_CONCAT 中使用 COUNT

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17463171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:04:01  来源:igfitidea点击:

Using COUNT in GROUP_CONCAT

mysqlsqlcountgroup-concat

提问by mesnicka

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.

我想要的结果应该是字符串 "3, 2, 3, 1" 因为这只是我复杂查询字符串的一部分。

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

错误编号: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.

我有一种感觉 COUNT、MAX、MIN 或 SUM 不能在 GROUP_CONCAT 中使用。如果是这样,你知道另一种方法来做到这一点。

回答by peterm

You need to COUNT()with GROUP BYin an inner select first and then apply GROUP_CONCAT()

你需要COUNT()GROUP BY在内部首先选择,然后应用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 SQLFiddledemo

这是SQLFiddle演示

回答by Naveen Kumar Alonekar

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

回答by Mudit Gupta

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.

这在我的情况下效果很好。