Friday, August 1, 2008

Count Male and Female in one query

Just a tip in sql query to count Male and Female in one single query..
I am having trouble in this problem when i was first took an examination in one of the company that i applied and i got wrong in this due to lack of idea... but i here is the solution on this..

Supposing you have a table Person_tbl with the fields

id,name,gender

Person_tbl
---------------------------------------------------------------------------
id | name | gender |
---------------------------------------------------------------------------
1 | Mike Enriquez | M |
2 | Marian Rivera | F |
3 | Lito Camo | M |
4 | Ping Lacson | M |
5 | Sarah Geronimo | F |
------------------------------------------------------------------------

You could do it by this query..

$query1= "Select count(*) AS Male from Person_tbl where gender='M'";

the $query1 would return the number of Males in the table Person_tbl which would return something like this...

-------
Male
-------
3
-------

and in the second query we could also do like this...
$query2= "Select count(*) AS Female from Person_tbl where gender='F'";

to get the number of females and it output something like this..

-------
Female
-------
2
-------

okay.. we can still achieved the number of males and females but we need it to do in 1 single query only.. So we can achieve that in a single query like this..


$query3="Select (Select count(*) from Person_tbl where gender='M') AS Male,
(Select count(*) from Person_tbl where gender='F') AS Female ";


By this query above it would output like this:

----------------------
Male | Female|
3 2
______________


so pretty simple...

1 comment:

magdalineeader said...

Sugarboo Extra Long Digital Titanium Styler - Titanium
Find the perfect sugarboo extra titanium pot long digital titanium styler titanium symbol in Tittori - Titanium Art. This titanium trim reviews T-40 T-40 T-40 T-40 T-40 T-40 T-40 T-40 T-40 T-40 titanium trimmer as seen on tv T-40 หาเงินออนไลน์ T-40 T-40 T-40