A table has following layout ; CITY, NAME , SEX How 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?
RE: A table has following layout ; CITY, NAME , SEX
select emp1.city emp1.male male emp2.female female from (select city count(sex) as male from emp where sex 'M' group by city) emp1 (select city count(sex) as female from emp where sex 'F' group by city) emp2 where emp1.city emp2.city and emp1.city 'NGP'
THIS QUERY WILL NOT WORK IF THERE IS NO MALE RECORD OR FEMALE RECORD .. ie there should be at least one male and one female in one city ..
can anybody has other option ... like if in City NGP there are males only then ... Output should be .. NGP 10 0 ... males 10 and NO females..or vice versa NGP 0 10 ..........???
RE: A table has following layout ; CITY, NAME , SEX
select (Select count(*) From tab where City 'XXX' and Sex 'Male') as Male_Cnt (Select count(*) From tab where City 'XXX' and Sex 'Male') as Female_Cnt From Dual
RE: A table has following layout ; CITY, NAME , SEX
select count(male.name) as malecount count(female.name) as femalecount from (select name from table where sex 'm') male (select name from table where sex 'f') female where city 'XXX';
RE: A table has following layout ; CITY, NAME , SEX
I think prafull's approach is fine.Another simple way of doing it is
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
RE: A table has following layout ; CITY, NAME , SEX
declare v_totalmale binary_integer; v_totalfemale binary_integer; begin select count(sex) into v_totalmale from test where city 'Delhi' and sex 'Male'; select count(sex) into v_totalfemale from test where city 'Dlehi' and sex 'Female'; dbms_output.put_line(' TotalMale' || ' ' || 'TotalFemale'); dbms_output.put_line(' ' || v_totalmale || ' '|| v_totalfemale); end;