简体   繁体   English

GROUP_CONCAT()中的CONCAT()计数

[英]CONCAT() inside GROUP_CONCAT() with count

I am trying to get results with group_concat, concat and count functions in MySQL but it gives me error. 我正在尝试在MySQL中使用group_concat,concat和count函数获取结果,但它给了我错误。 here is my table 这是我的桌子

在此处输入图片说明

First, when I try to get count and status with concat, it works fine. 首先,当我尝试通过concat获取计数和状态时,它可以正常工作。

$query="SELECT CONCAT(`status`,':',count(status)) FROM `mytable` GROUP BY status"

output: 输出:
Hold:2 按住:2
Completed:3 完成:3
Cancelled:2 取消:2

It's all fine till here. 到这里都很好。 Now I want this output in one row. 现在,我希望此输出成一行。 So I tried using GROUP_CONCAT(). 所以我尝试使用GROUP_CONCAT()。

$query="SELECT GROUP_CONCAT(CONCAT(`status`,':',count(status)) SEPARATOR ',') as rowString FROM `mytable` GROUP BY status"

but now its giving me error " Invalid use of group functions" 但现在它给我错误“组功能的无效使用”

Note: the same query works if I replace count(status) with some other field from table ( without count). 注意:如果我将count(status)替换为表中的其他字段(不包括count),则可以使用相同的查询。 The count() function is causing some problem when used in this manner. 当以这种方式使用时, count()函数会引起一些问题。

Desired Output 期望的输出

Hold:2,Completed:3,Cancelled:2 保持:2,完成时间:3,取消:2

Appreciate your help. 感谢您的帮助。

You cannot nest aggregation functions ( count() is in the arguments to group_conat() ). 您不能嵌套聚合函数( count()group_conat()的参数中)。 One solution is to select from a nested subquery. 一种解决方案是从嵌套子查询中进行选择。

SELECT group_concat(status, ':', count SEPARATOR ',') rowstring
       FROM (SELECT status,
                    count(*) count
                    FROM mytable
                    GROUP BY status) x;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM