Choosing a column that fulfills many conditions in different records

前端 未结 2 1752
独厮守ぢ
独厮守ぢ 2021-01-24 07:54

I have got table like this:

+----------+---------+
| Customer | Product |
+----------+---------+
|        1 |       1 |
|        1 |       2 |
|        1 |               


        
相关标签:
2条回答
  • 2021-01-24 08:41

    You can GROUP BY on the Customer and use conditional aggregation based filtering inside the Having clause. MySQL automatically casts boolean values to 0/1 when using in numeric context.

    In order to have a specific Product bought by a Customer, its SUM(Product = ..) should be 1.


    Case 1: Get those customers which have purchased each one of the 1,2,3 products at-least (they may have purchased other products as well).

    SELECT Customer
    FROM your_table
    GROUP BY Customer
    HAVING SUM(Product = 1) AND -- 1 should be bought
           SUM(Product = 2) AND -- 2 should be bought
           SUM(Product = 3)     -- 3 should be bought
    

    If you want exclusivity, i.e., the customer has not bought any other product other than 1,2,3; then you can use the following instead.

    Case 2: Get those customers which have purchased only 1,2,3 products and each one of them has been purchased at-least once.

    SELECT Customer
    FROM your_table
    GROUP BY Customer
    HAVING SUM(Product = 1) AND  -- 1 should be bought
           SUM(Product = 2) AND  -- 2 should be bought
           SUM(Product = 3) AND  -- 3 should be bought
           NOT SUM(Product NOT IN (1,2,3))  -- anything other 1,2,3 should not be bought
    
    0 讨论(0)
  • 2021-01-24 08:43

    if you want the customer who bought all the 3 product you could use aggregation function count(distinct product)

        SELECT Customer
        FROM your_table
        where product in (1,2,3)
        GROUP BY Customer
        HAVING count(distinct product) = 3
    
    0 讨论(0)
提交回复
热议问题