anon
anon

Reputation: 865

MYSQL count in select statement

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 ?

Upvotes: 3

Views: 163

Answers (2)

Geoff Montee
Geoff Montee

Reputation: 2597

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;

Upvotes: 2

Adriaan Stander
Adriaan Stander

Reputation: 166336

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

Upvotes: 5

Related Questions