Consultation to calculate the number of female and male students

Asked

Viewed 472 times

0

In this consultation I would use the GROUP BY?

That and the model inserir a descrição da imagem aqui

  • Yes, with group by. Have you tried something? If yes, post in the question the query and the results you got.

  • Do you want the number of students enrolled in some course of some discipline, or all students independent of that? Etc...

1 answer

2


Translate the table Aluno of its model to PL/PgSQL:

CREATE TABLE Aluno
(
  idaluno BIGINT PRIMARY KEY,
  nome TEXT NOT NULL,
  cpf VARCHAR(11) NOT NULL,
  rg VARCHAR(14) NOT NULL,
  sexo VARCHAR(1) NOT NULL,
  data_nascimento DATE NOT NULL
); 

Registering Students:

INSERT INTO Aluno ( idaluno, nome, cpf, rg, sexo, data_nascimento ) VALUES
( 100, 'JOAO', '11122233300', '1234567', 'M', '1980-03-10' ),
( 200, 'JESUS', '99988877766', '45678', 'M', '1970-06-17' ),
( 300, 'MARIA', '44455566677', '09876', 'F', '1953-04-30' ),
( 400, 'MADALENA', '33399955511', '345677', 'F', '1965-10-23' ),
( 500, 'JOSE', '00987243643', '8181818', 'M', '1988-03-03' );

Solution #1: With GROUP BY and count():

SELECT
  sexo,
  COUNT(1)
FROM
  Aluno
GROUP BY
  sexo;

Exit:

| sexo | count |
|------|-------|
|    F |     2 |
|    M |     3 |

Solution #2: With sum() and without GROUP BY:

SELECT
   SUM(CASE WHEN sexo = 'M' THEN 1 ELSE 0 END) AS qtd_masculino,
   SUM(CASE WHEN sexo = 'F' THEN 1 ELSE 0 END) AS qtd_feminino,
   SUM(1) AS qtd_total
FROM
  Aluno;

Exit:

| qtd_masculino | qtd_feminino | qtd_total |
|---------------|--------------|-----------|
|             3 |            2 |         5 |

Sqlfiddle: http://sqlfiddle.com/#! 17/557d1/2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.