query to get the count of Male, count of female in a given city

Que : A table has following layout ; CITY, NAME , SEXHow do you write a query to get the count of Male, count of female in a given city XXX.Query result should be in a single row with count of male , count of female as columns?



Ans :-
-------------------------------------------------
SELECT CITY, COUNT(MALE), COUNT(FEMALE)
FROM
( SELECT  CITY,
  case  WHEN SEX='M' THEN  'M' ELSE NULL  END  MALE,
   case WHEN SEX='F'  THEN  'F'  ELSE NULL   END  FEMALE
   FROM TAB_PT
)
GROUP BY CITY

------------------------------------or-------------------------------------------------

select city,(count(case when gender = 'Male' then 1 else 0 end)) 'male',
(count(case when gender = 'Female' then 1 else 0 end)) 'female'
from table
where city = 'give the city'



Comments