简体   繁体   中英

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. here is my table

在此处输入图片说明

First, when I try to get count and status with concat, it works fine.

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

output:
Hold:2
Completed:3
Cancelled:2

It's all fine till here. Now I want this output in one row. So I tried using 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). The count() function is causing some problem when used in this manner.

Desired Output

Hold:2,Completed:3,Cancelled:2

Appreciate your help.

You cannot nest aggregation functions ( count() is in the arguments to 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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