getting count from the same column in a mysql table?

后端 未结 4 790
野趣味
野趣味 2021-01-03 00:07

I wanted to a count of the same field for different values for example:

user{user_id, gender}

Gender can have obviously male or

相关标签:
4条回答
  • 2021-01-03 00:32

    Try this query -

    SELECT
      COUNT(IF(gender = 'M', User_id, NULL) males,
      COUNT(IF(gender = 'F', User_id, NULL) females
    FROM
      User
    
    0 讨论(0)
  • 2021-01-03 00:39

    try this: with total count:

    Select gender,count(*) as count
    From User
    Group by gender
    with rollup
    

    SQl Fiddle demo

    0 讨论(0)
  • 2021-01-03 00:44

    Try this for row wise result:

    SELECT gender, COUNT(User_id) AS count
    FROM User
    GROUP BY gender;
    

    Output:

    | gender | count |
    |--------|-------|
    |      F |     4 |
    |      M |     2 |
    

    Try this for row wise result with grand total:

    SELECT  (IFNull(gender,'Total')) AS gender,
    COUNT(User_id) AS Count
    FROM User
    GROUP BY gender
    WITH rollup;
    

    Output:

    | gender | Count |
    |--------|-------|
    |      F |     4 |
    |      M |     2 |
    |  Total |     6 |
    

    Try this for column wise result:

    SELECT
      COUNT(CASE WHEN gender = 'M' THEN User_id END) AS males,
      COUNT(CASE WHEN gender = 'F' THEN User_id END) AS females,
      COUNT(*) AS Total
    FROM User;
    

    Output:

    | males | females | Total |
    |-------|---------|-------|
    |     2 |       4 |     6 |
    

    See this SQLFiddle

    0 讨论(0)
  • 2021-01-03 00:52

    Based on your comment, you want count for both males, females and the total count:

    SELECT sum(case when gender = 'M' then 1 else 0 end) males,
      sum(case when gender = 'F' then 1 else 0 end) females,
      count(*) total
    FROM  yourTable
    

    See SQL Fiddle with Demo

    0 讨论(0)
提交回复
热议问题