Count distinct values

前端 未结 5 1348

I have a data set asking a customer how many pets they have for example. Is there a way with one query I can count the distinct values (1,2,3, etc)? Thanks!

         


        
5条回答
  •  生来不讨喜
    2020-12-07 17:49

    Ok, I deleted my previous answer because finally it was not what willlangford was looking for, but I made my point that maybe we were all misunderstanding the question.

    I also thought of the SELECT DISTINCT... thing at first, but it seemed too weird to me that someone needed to know how many people had a different number of pets than the rest... thats why I thought that maybe the question was not clear enough.

    So, now that the real question meaning is clarified, making a subquery for this its quite an overhead, I would preferably use a GROUP BY clause.

    Imagine you have the table customer_pets like this:

    +-----------------------+
    |  customer  |   pets   |
    +------------+----------+
    | customer1  |    2     |
    | customer2  |    3     |
    | customer3  |    2     |
    | customer4  |    2     |
    | customer5  |    3     |
    | customer6  |    4     |
    +------------+----------+
    

    then

    SELECT count(customer) AS num_customers, pets FROM customer_pets GROUP BY pets
    

    would return:

    +----------------------------+
    |  num_customers  |   pets   |
    +-----------------+----------+
    |        3        |    2     |
    |        2        |    3     |
    |        1        |    4     |
    +-----------------+----------+
    

    as you need.

提交回复
热议问题