简体   繁体   中英

SQL using group_concat with count of each concatenated item rather total count in a row

MYSQl - Count of elements inside Group_Concat

I rewrote it as this fiddle , but its giving error.

Anyone can help?

As far as concerns, to solve the error and get the correct result, you just need to return the CUSTOMERID from the aggregated subquery (the column is already part of the GROUP BY clause).

Updated query:

 SELECT SELLER, 
       COUNT(*) as COUNT_OF_CUSTIDS,
       GROUP_CONCAT(CUSTOMERID, ' (', cnt, ')' SEPARATOR '|') AS CUSTIDS
FROM (
    SELECT SELLER, CUSTOMERID, COUNT(*) as cnt
    FROM docs
    GROUP BY SELLER, CUSTOMERID
) t
GROUP BY SELLER
HAVING COUNT(*) > 1

Returns:

| SELLER | COUNT_OF_CUSTIDS | CUSTIDS              |
| ------ | ---------------- | -------------------- |
| S1     | 3                | C2 (2)|C1 (2)|C3 (3) |
| S2     | 3                | C3 (1)|C2 (1)|C1 (2) |

Demo on DB Fiddle

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