MySQL distinct count if conditions unique

后端 未结 2 927
耶瑟儿~
耶瑟儿~ 2021-01-31 09:36

I am trying to build a query that tells me how many distinct women and men there are in a given dataset. The person is identified by a number \'tel\'. It is possible for the sam

2条回答
  •  后悔当初
    2021-01-31 09:46

    There is another solution similar to @segeddes's second solution

    Select COUNT(DISTINCT tel) as gender_count, 
           COUNT(DISTINCT IF(gender = "male", tel, NULL)) as male_count, 
           COUNT(DISTINCT IF(gender = "female", tel, NULL)) as female_count 
    FROM example_dataset
    

    Explanation :

    IF(gender = "male", tel, NULL)
    

    Above expression will return tel if gender is male else it will return NULL value

    Then we've

    DISTINCT
    

    It will remove all the duplicates

    And finally

    COUNT(DISTINCT IF(gender = "male", tel, NULL))
    

    Will count all the distinct occurrences of rows having male gender

    Note : SQL COUNT function with expression only counts rows with non NULL values, for detailed explanation check - http://www.mysqltutorial.org/mysql-count/

提交回复
热议问题