【问题标题】:counting distinct and repetitions mysql计算不同和重复mysql
【发布时间】:2014-04-01 06:10:24
【问题描述】:

我想问一下如何在mysql中计算不同和重复

例如表格是这样的

主表

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

使用此代码

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

结果是

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

但结果应该是这样的(意思是如果没有重复则为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

谢谢

【问题讨论】:

    标签: mysql sql count unique


    【解决方案1】:

    试试这个:

    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
    

    结果:

    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
    

    Fiddle 中查看结果。

    【讨论】:

    • 真的需要 unique_purchasers 列吗?
    • @swapnil7:询问 OP。我只是提供了他正在寻找的东西。在我看来,在这种情况下,COUNT(DISTINCT col) 总是返回 1。
    • 你是对的,但似乎不需要在结果中添加该列
    • @swapnil7:我告诉过你,我只是帮助 OP 获得他想要的东西。我想,他需要那种输出。
    猜你喜欢
    • 2013-04-26
    • 2018-11-15
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 2018-11-15
    • 2020-05-17
    • 2016-08-21
    相关资源
    最近更新 更多