0

I have table named Students in PostgreSQL. In that table i have StudId, StudName and Gender columns. I want to get the number of male and female students in the table in a single result set in a function.

StudId   StudName    Gender
101      Peter       M
102      George      M
103      Mary        F
104      Rose        F

I already done this with SQL Server and MySQL. But I don't have any idea to do this with PostgreSQL.

I'm newer one to PostgreSQL, someone helps to finds the results. Thanks in advise.

0

1 Answer 1

2

Use two sub-selects like this

select (select count(*) cnt_male from tbl where gender='M') 
      ,(select count(*) cnt_female from tbl where gender='F')

or

You can use case in count() function like this

select count(case when gender='M' then 1 end) cnt_male
      ,count(case when gender='F' then 1 end) cnt_female 
from tbl

Result:

cnt_male cnt_female 
-------- ---------- 
2        2          

Edit:

as per op's update

create function fn_gender_cnt() returns table(tot_male bigint,tot_female bigint)
as
$$

  select count(case when gender='M' then 1 end) cnt_male
      ,count(case when gender='F' then 1 end) cnt_female 
from tbl

$$
language sql

usage:

select * from fn_gender_cnt();

result:

    tot_male tot_female 
    -------- ---------- 
    2        2   
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Friend. I found the logic already, but I don't know how to get the two results in a Function. Sorry for the mistake, now I update the Question.
@DineshDB I've updated my answer ...added a function to get the counts, is that what you were looking for??
Yes, thank you so much for your help. It works pretty good... Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.