SQL使用group_concat的每个连接项的计数而不是行中的总数

时间:2019-03-18 15:21:37

标签: mysql database count mariadb group-concat

MYSQl - Count of elements inside Group_Concat

我将其重写为 this fiddle ,但出现错误。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

关于问题,要解决该错误并获得正确的结果,您只需要从聚合子查询中返回CUSTOMERID(该列已经是GROUP BY子句的一部分)。 / p>

更新的查询:

 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

返回:

| 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