In this query would I use GROUP BY
?
I translate the Aluno
table of your 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;
Output:
| 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;
Output:
| qtd_masculino | qtd_feminino | qtd_total |
|---------------|--------------|-----------|
| 3 | 2 | 5 |
SQLFiddle: link