Pergunta

i would like to ask how to count distinct and repetitions in mysql

for example table looks like this

main_table

id      product_id   purchaser_id  
1       1               1
2       1               1          
3       1               1 
4       1               2
 5      1               2
 6      1               3
 7      2               1  
 8      2              2 
9       2             2
10      2             2
11       2            2
12      2             3
13       2           3
14      2            3
15     2             3
16     2             4
17      2            4

using this code

SELECT a.product_id,a.purchaser_id, 
       COUNT(DISTINCT a.purchaser_id) AS unique_purchasers, 
       COALESCE(c.totalCount,0) AS repeat_purchasers 
FROM main_table a 
    LEFT JOIN ( SELECT product_id, COUNT(totalCOunt) totalCount 
                FROM ( SELECT product_id, purchaser_id, COUNT(*) totalCOunt 
                        FROM main_table GROUP BY product_id, purchaser_id 
                        HAVING COUNT(*) > 1 ) s GROUP BY product_id ) c 
            ON a.product_id = c.product_id GROUP BY product_id, purchaser_id

result is

product_id  purchaser_id    unique_purchasers   repeat_purchasers   
1   1   1   2
1   2   1   2
1   3   1   2
2   1   1   3
2   2   1   3
2   3   1   3
2   4   1   3

but result should be like this(meaning if no repeat then 0)

product_id  purchaser_id    unique_purchasers   repeat_purchasers   
1   1   1   2
1   2   1   1
1   3   1   0
2   1   1   0
2   2   1   3
2   3   1   3
2   4   1   1

thank you

Foi útil?

Solução

Try this:

SELECT a.product_id,a.purchaser_id, 
       COUNT(DISTINCT a.purchaser_id) AS unique_purchasers,
       c.totalcount as repeat_purchasers
FROM main_table a 
INNER JOIN (SELECT product_id, purchaser_id, COUNT(*)-1 totalCOunt 
                        FROM main_table GROUP BY product_id, purchaser_id 
                ) C ON C.product_id=a.product_id AND a.purchaser_id=C.purchaser_id             
GROUP BY product_id, purchaser_id

Result:

PRODUCT_ID  PURCHASER_ID    UNIQUE_PURCHASERS   REPEAT_PURCHASERS
1           1               1                   2
1           2               1                   1
1           3               1                   0
2           1               1                   0
2           2               1                   3
2           3               1                   3
2           4               1                   1

See result in Fiddle.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top