简体   繁体   English

MYSQl-Group_Concat中的元素计数

[英]MYSQl - Count of elements inside Group_Concat

I'm quite new to MYSQL and would need a little help in the group_concat statement. 我是MYSQL的新手,在group_concat语句中需要一些帮助。 I have the below table 我有下表

Seller Merchant CustomerID
S1     M1       C1
S1     M1       C1
S1     M1       C2
S1     M1       C3
S1     M1       C4
S2     M2       C5
S2     M2       C6
S3     M3       C6

For the combination of same seller and merchant, all the items which has different customerIDs along with the count of how many times it is repeated. 对于同一卖方和商人的组合,所有具有不同客户ID的商品以及其重复次数的计数。

I'm able to derive count of unique customer IDS using group_concat but not able to get the count. 我可以使用group_concat得出唯一客户IDS的计数,但无法获得计数。

SELECT * , LENGTH(CUSTIDS) - LENGTH(REPLACE(CUSTIDS,',',''))+1 AS COUNT_OF_CUSTIDS
FROM (SELECT SELLER, MERCHANT, GROUP_CONCAT(CUSTOMERID SEPARATOR '|') AS CUSTIDS
FROM TABLE
GROUP BY SELLER, MERCHANT
HAVING COUNT(DISTINCT CUSTOMERID ) >1 
)

which gives me the below result 这给了我下面的结果

Seller Merchant CustomerID    COUNT_OF_CUSTIDS
S1     M1       C1,C2,C3,C4   4
S2     M2       C5,C6         2

whereas I would want the below 而我想要以下

Seller Merchant CustomerID                 COUNT_OF_CUSTIDS
S1     M1       C1(2),C2(1),C3(1),C4(1)    4
S2     M2       C5(1),C6(1)                2

You need to first aggregate at the seller / merchant / customerid level to get the count. 您需要先在seller / merchant / customerid级别进行汇总才能获得计数。 Then you can continue with your aggregation: 然后,您可以继续进行聚合:

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

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

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