3

I have data in database like this

id  class  gender
1     A      F
2     B      F
3     A      M
4     A      F
5     A      M
6     B      M
7     A      F

From this data I want to make select statement to produce report like this

_________________________
        Gender
class   M    F     Total
_________________________
A       2    3       5
B       1    1       2
_________________________
TOTAL   3    4       7

How can I make that select statement ?

2
  • 4
    the primary purpose of having a database server is to store the data, not for generating report, the counts are possible but by formatting makes it difficult, why not do it on your application level? Commented Oct 10, 2012 at 4:22
  • Thanks, now I get some idea. I will count the total in the application. But how can I get total gender based on class ? Commented Oct 10, 2012 at 4:32

2 Answers 2

5

Have a look at the following example

SQL Fiddle DEMO

SELECT class,
      SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) `M`,
      SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) `F`,
      COUNT(1) Total
FROM Table1
GROUP BY class
Sign up to request clarification or add additional context in comments.

Comments

2

To get totals for each gender:

SELECT class, gender, COUNT(*) as gender_count
FROM Gender
GROUP BY class, gender;

To get total:

SELECT class, COUNT(*) as total_count
FROM Gender
GROUP BY class;

Comments

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.