Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have condition inside count SQL?

I already tried this code:

    SELECT Count(Gender) As MaleCount, Count(Gender) As FemaleCount
    FROM [Session4].[dbo].[Survey]
    Where Gender = 'M' or Gender = 'F' 

I can't get the accurate data when counting with two different conditions in one query.

Pictures below:

This is the result.

enter image description here

This is the original data

SELECT  TOP (1000) [Departure]
    ,[Arrival]
    ,[Age]
    ,[Gender]
    ,[CabinType]
    ,[Q1]
    ,[Q2]
    ,[Q3]
    ,[Q4]
FROM [Session4].[DBO].[Survey]

enter image description here

like image 781
Christian Lumugdan Avatar asked Sep 05 '25 01:09

Christian Lumugdan


1 Answers

count explain :

  • COUNT(*) counts all rows
  • COUNT(column) counts non-null value
  • COUNT(distinct column) counts distinct non-null value
  • COUNT(1) is the same as COUNT(*)

Use case/when + sum :

SELECT
    sum(case when Gender = 'M' then 1 else 0 end ) As MaleCount,
    sum(case when Gender = 'F' then 1 else 0 end ) As FemaleCount
FROM [Session4].[dbo].[Survey]

will produce somethings like this :

MaleCount | FemaleCount
1000      | 1255

Another way is using simple goup by

SELECT
    Gender,
    Count(*)
FROM [Session4].[dbo].[Survey]
GROUP BY
    Gender

will produce :

Gender | Count
M      | 1000
F      | 1255
like image 79
Indent Avatar answered Sep 07 '25 12:09

Indent