Estoy trabajando en la siguiente tabla de usuarios, donde el rol = 2 significa que el usuario es un instructor y el rol = 3 significa que el usuario es un estudiante.
+--------+------+---------------+ | name | role | creation_date | +--------+------+---------------+ | Tom | 2 | 2020-07-01 | | Diana | 3 | 2020-07-01 | | Rachel | 3 | 2020-07-01 | | Michel | 3 | 2020-08-01 | +--------+------+---------------+Mi objetivo es seleccionar el valor de la suma de todos los instructores y estudiantes, agrupados por fecha. El resultado debería verse así:
+------------------+---------------+---------------+ | totalInstructors | totalStudents | creation_date | +------------------+---------------+---------------+ | 1 | 2 | 2020-07-01 | | 0 | 1 | 2020-08-01 | +------------------+---------------+---------------+En este caso, el 01-07-2020 tenía 1 instructor y 2 alumnos registrados y el 01-08-2020 no tenía instructores y tenía 1 alumno registrado.
Mi problema es que estoy teniendo dificultades para configurar esta consulta, si alguien me puede ayudar muchas gracias!
Usar agregación condicional:
SELECT creation_date, COUNT(CASE WHEN role = 2 THEN 1 END) AS totalInstructors, COUNT(CASE WHEN role = 3 THEN 1 END) AS totalStudents FROM yourTable GROUP BY creation_date;Necesitaría contar con una declaración de caso de la siguiente manera
select count(case when role=2 then 1 end) as totalInstructors ,count(case when role=3 then 1 end) as totalStudents ,creation_date from tbl group by creation_dateUn simple GRoupBY y SUM ayuda
Esto funciona. porque el rol de comparación = 2 devuelve 1 si es verdadero y 0 si es falso
CREATE TABLE table1 ( `name` VARCHAR(6), `role` INTEGER, `creation_date` VARCHAR(10) ); INSERT INTO table1 (`name`, `role`, `creation_date`) VALUES ('Tom', '2', '2020-07-01'), ('Diana', '3', '2020-07-01'), ('Rachel', '3', '2020-07-01'), ('Michel', '3', '2020-08-01');
SELECT SUM(`role` = 2) totalInstructors , SUM(`role` = 3) totalStudents, `creation_date` FROM table1 GROUP BY `creation_date` ORDER BY `creation_date`totalInstructores | totalEstudiantes | fecha de creación ---------------: | ------------: | :------------ 1 | 2 | 2020-07-01 0 | 1 | 2020-08-01
db<>violín aquí