Bienvenida conceptos básicos y contexto histórico de las Bases de Datos

1

Bienvenida conceptos básicos y contexto histórico de las Bases de Datos

2

Playground: tu primera consulta en bases de datos

Introducción a las bases de datos relacionales

3

Historia de las bases de datos relacionales

4

Qué son entidades y atributos

5

Entidades de Platzi Blog

6

Relaciones

7

Múltiples muchos

8

Diagrama ER

9

Diagrama Físico: tipos de datos y constraints

10

Diagrama Físico: normalización

11

Formas normales en Bases de Datos relacionales

12

Diagrama Físico: normalizando Platziblog

RDBMS (MySQL) o cómo hacer lo anterior de manera práctica

13

¿Qué es RDB y RDBMS?

14

Instalación local de un RDBMS (Windows)

15

Instalación local de un RDBMS (Mac)

16

Instalación local de un RDBMS (Ubuntu)

17

Clientes gráficos

18

Servicios administrados

SQL hasta en la sopa

19

Historia de SQL

20

DDL create

21

Playground: CREATE TABLE

22

CREATE VIEW y DDL ALTER

23

DDL drop

24

Playground: VIEW, ALTER y DROP en SQL

25

DML

26

Playground: CRUD con SQL

27

¿Qué tan standard es SQL?

28

Creando Platziblog: tablas independientes

29

Creando Platziblog: tablas dependientes

30

Creando Platziblog: tablas transitivas

Consultas a una base de datos

31

¿Por qué las consultas son tan importantes?

32

Estructura básica de un Query

33

SELECT

34

Playground: SELECT en SQL

35

FROM y SQL JOINs

36

Utilizando la sentencia FROM

37

Playground: FROM y LEFT JOIN en SQL

38

WHERE

39

Utilizando la sentencia WHERE nulo y no nulo

40

Playground: Filtrando Datos con WHERE

41

GROUP BY

42

ORDER BY y HAVING

43

Playground: Agrupamiento y Ordenamiento de Datos

44

El interminable agujero de conejo (Nested queries)

45

¿Cómo convertir una pregunta en un query SQL?

46

Preguntándole a la base de datos

47

Consultando PlatziBlog

48

Playground: Prueba Final con PlatziBlog

Introducción a la bases de datos NO relacionales

49

¿Qué son y cuáles son los tipos de bases de datos no relacionales?

50

Servicios administrados y jerarquía de datos

Manejo de modelos de datos en bases de datos no relacionales

51

Top level collection con Firebase

52

Creando y borrando documentos en Firestore

53

Colecciones vs subcolecciones

54

Recreando Platziblog

55

Construyendo Platziblog en Firestore

56

Proyecto final: transformando tu proyecto en una db no relacional

Bases de datos en la vida real

57

Bases de datos en la vida real

58

Big Data

59

Data warehouse

60

Data mining

61

ETL

62

Business intelligence

63

Machine Learning

64

Data Science

65

¿Por qué aprender bases de datos hoy?

Bonus

66

Bases de datos relacionales vs no relacionales

67

Elegir una base de datos

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Playground: Agrupamiento y Ordenamiento de Datos

43/67

Aportes 139

Preguntas 3

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Una pequeña correccion: en la descripcion del problema, en el primer item, en vez de decir que la tabla se llama teachers (en plural) dice que se llama teacher (en singular)

SELECT
  teachers.name AS teacher,
  SUM(courses.n_reviews) AS total_reviews
FROM teachers
INNER JOIN courses
ON teachers.id = courses.teacher_id
GROUP BY teacher
ORDER BY total_reviews DESC;

Les dejo mi analisis y solucion:

  • Tengo dos tablas:

    • courses: id, name, n_reviews y teacher_id
    • teachers: id y name.

    (De lo anterior sabemos que courses.teacher_id y teachers .id son lo mismo, por lo que haremos un INNER JOIN hacioendo coincidir estos dos valores)
    FROM teachers
    INNER JOIN courses ON teachers.id = courses.teacher_id

  • Nos piden SELECCIONAR la SUMA total de reviews en todos los cursos por cada profesor. Es decir:

    • SELECT teachers. name, SUM(courses.n_reviews).
      En este punto, vale aclarar que nos piden nombrar estos puntos, por lo que:

    SELECT teachers.name AS teacher, SUM (courses.n_reviews) AS total_reviews

  • Piden AGRUPAR por profesores para luego ORDENAR:
    GROUP BY courses.teacher_id

  • ORDENAR de forma DESCENDENTE el total de reviews (total_reviews) que encontramos anteriormente:
    ORDER BY total_reviews DESC

  • Por ultimo, las reviews deben ser mayores a 0. Lo hacemos con HAVING ya que es una coluimna que se genera despues:
    HAVING total_reviews > 1

Basandonos en lo anterior, organizando la informacion en el orden correcto (ver la clase anterior) la solucion a la que llegue seria:

SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviews
FROM teachers
INNER JOIN courses ON teachers.id = courses.teacher_id
GROUP BY courses.teacher_id
HAVING total_reviews > 1
ORDER BY total_reviews DESC;

Estan a otro nivel los retos, no pude 😦
Al menos los intenté.

Despues de media hora y dos dias de repaso me salio, lagrimas de felicidad :’)


SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviews
FROM courses
RIGHT JOIN teachers ON teachers.id = courses.teacher_id
WHERE teacher_id IS NOT NULL
GROUP BY teacher
ORDER BY total_reviews DESC
; 

Mi Solución
.
.
.
.

<SELECT teachers.name AS teacher,SUM(courses.n_reviews) AS total_reviews
FROM teachers 
inner join courses ON teachers.id = courses.teacher_id
GROUP BY courses.teacher_id
ORDER BY total_reviews DESC;
> 

Solución… 😄
.

.
.
.
.
.
.

SELECT t.name AS teacher, SUM(c.n_reviews) AS total_reviews
FROM teachers AS t
INNER JOIN courses AS c ON t.id = c.teacher_id
GROUP BY c.teacher_id
ORDER BY total_reviews DESC;

Les comparto el código de la prueba con comentarios de los pasos para que lo puedan entender mejor 😃

Mi solucion
.
.
.
.
.
.
.
.
.
.

SELECT 
  teachers.name AS teacher,
  SUM(n_reviews) AS total_reviews
FROM teachers  
INNER JOIN courses
ON teachers.id = courses.teacher_id
GROUP BY teachers.name
ORDER BY total_reviews DESC;

Fue un reto realmente…
Espero lo intentes pero si te frusta por acá te dejo mi solución, la idea es que puedas analizarlo y no solo transcribir la respuesta.


Mi técnica es ir de menos a más… es decir tomo la parte más sencilla del requerimiento y voy probando que funcione, así le voy agregando las funcionalidades más complejas del requerimiento hasta completarlo, de esta manera en todo momento estoy seguro hasta que punto el desarrollo está funcionando y voy solucionando cada problema o error que se va presentando!

Un humilde aporte. Si en la sumatoria se quisiera tener en cuenta solo aquellos cursos con mas de "N" reviews (ej: N=150), eso se podría incluir usando un WHERE como filtro tal como detallo debajo: `SELECT t.name AS teacher,SUM(c.n_reviews) AS total_reviews ` `FROM teachers AS t ` `INNER JOIN courses AS c` `ON c.teacher_id = t.id` `WHERE c.n_reviews > 150` `GROUP BY teacher` `ORDER BY total_reviews DESC;` ![](https://static.platzi.com/media/user_upload/image-8bf5369d-f31a-4b92-a691-e3b5978adbe7.jpg) Como se puede ver, al comparar los resultados devueltos CON y SIN ese filtro el unico Profesor al que le cambia la cantidad de reviews es a Israel ya que es el unico que tiene un curso con no mas de 150 reviews.

Les dejo mi solución, me lanza como error pero me sale el mismo resultado.

<select 
t.name teacher,
sum(c.n_reviews) total_reviews
FROM teachers t
LEFT JOIN courses c ON t.id = c.teacher_id
WHERE c.teacher_id IS NOT NULL
GROUP BY t.name
ORDER BY total_reviews DESC;
> 

Los ejercicios en el playground deberían revisarse en la prueba por el resultado que arrojas, ya que si lo haces algo diferente me da error y luego al correr la solución que presentan en el ejercicio obtengo la misma respuesta que con el código que escribí, pero igual al correr la prueba me sale que hay errores.

Estos playground son de lo mejor que pudieron hacer en platzi!! te imaginas que tuvieran mas de un ejercicio? o un mega ejercicio complementario tipo entrevista ?
esta de locos !
Mi solución:

SELECT teachers.name AS teacher,SUM(courses.n_reviews) total_reviews
FROM courses
INNER JOIN teachers ON  courses.teacher_id = teachers.id
GROUP BY teacher
ORDER BY total_reviews DESC

En mi caso usé la sentencia where/having para considerar la restricción de no contar cursos sin al menos un review. Sé que en este caso es redundante porque los cursos sin reviews implícitamente se sumarán como 0 y dará igual el resultado, pero en caso de no contar reviews sino otra columna (como cantidad de cursos por profesor) sí sería necesario agregar la restricción.

select 
  teachers.name as teacher, 
  sum(courses.n_reviews) as total_reviews
from teachers
inner join courses on teachers.id = courses.teacher_id
where courses.n_reviews >= 1 -- omitir si se usa having y viceversa
group by teacher
--having total_reviews >= 1
order by total_reviews desc;

Con las tablas/entidades abreviadas… 😊

Muy revueltas las instrucciones...
Agrego abajo mi solución, para alguien que necesite ayuda. . . . . . ```js -- Escribe tu código aquí 👇 -- SELECT * FROM courses; -- SELECT * FROM teachers; SELECT t.name AS teacher, SUM(c.n_reviews) AS total_reviews FROM teachers t INNER JOIN courses c ON t.id = c.teacher_id WHERE c.n_reviews >= 1 GROUP BY t.id, t.name ORDER BY total_reviews DESC; ```
Les comparto mi solución: ![](https://static.platzi.com/media/user_upload/image-11ce57f4-59e7-4da0-915d-ddea828c2e55.jpg)
SELECT t.name as teacher,sum(c.n\_reviews) as total\_reviews FROM courses as c INNER JOIN teachers as t on t.id = c.teacher\_id GROUP BY teacher having total\_reviews > 0 order by total\_reviews desc
SELECT teachers.name AS teacher, SUM(courses.n\_reviews) AS total\_reviewsFROM coursesRIGHT JOIN teachers ON teachers.id = courses.teacher\_idWHERE teacher\_id IS NOT NULLGROUP BY teacherORDER BY total\_reviews DESC;
SELECT teachers.name AS teacher, SUM(courses.n\_reviews) AS total\_reviews FROM teachers JOIN courses ON teachers.id = courses.teacher\_id WHERE courses.n\_reviews >= 1 GROUP BY teachers.name ORDER BY total\_reviews DESC;
La verdad me costó el reto, pero lo resolví esta es mi solución: SELECT teachers.name AS teacher, SUM(courses.n\_reviews) AS total\_reviews FROM teachers INNER JOIN courses ON teachers.id = courses.teacher\_id GROUP BY teacher HAVING total\_reviews = SUM(courses.n\_reviews) ORDER BY total\_reviews DESC;
Para resolver este ejercicio en SQL, vamos a realizar los siguientes pasos: 1. Filtrar los cursos que tienen al menos 1 review. 2. Hacer una unión entre la tabla de cursos y la tabla de profesores. 3. Agrupar los resultados por el nombre del profesor y sumar las reviews de todos sus cursos. 4. Ordenar el resultado por la suma total de reviews en orden descendente. Aquí está la consulta SQL para lograrlo: SELECT t.name AS teacher, SUM(c.n\_reviews) AS total\_reviews FROM courses c JOIN teachers t ON c.teacher\_id = t.id WHERE c.n\_reviews > 0 GROUP BY t.name ORDER BY total\_reviews DESC; Desglose de la consulta: * `SELECT t.name AS teacher, SUM(c.n_reviews) AS total_reviews`: Selecciona el nombre del profesor y la suma de las reviews. * `FROM courses c JOIN teachers t ON c.teacher_id = t.id`: Realiza una unión (join) entre las tablas `courses` y `teachers` en base al `teacher_id`. * `WHERE c.n_reviews > 0`: Filtra los cursos para considerar solo aquellos con al menos 1 review. * `GROUP BY t.name`: Agrupa los resultados por el nombre del profesor. * `ORDER BY total_reviews DESC`: Ordena los resultados de forma descendente en base a la suma total de reviews.
Alguien me puede ayudar con esta duda. La Guia dice contar la cantidad de reviews. ¿Por qué la solución se hace con una SUMA? ![](https://static.platzi.com/media/user_upload/image-7821e9db-4d6a-44c8-a88b-de4c72c252e1.jpg)![](https://static.platzi.com/media/user_upload/image-ce513e3f-19f4-4c94-9c7c-c17506a84816.jpg)Este es mi ejercicio, pero me aparece que algo salio mal en las pruebas ![](https://static.platzi.com/media/user_upload/image-869ac694-2b5c-40db-9f94-96c749634601.jpg)
Aqui mi solucion: ``` \-- Escribe tu código aquí 👇SELECT teachers.name AS teacher, SUM(n\_reviews) AS total\_reviewsFROM coursesJOIN teachers ON teachers.id = courses.teacher\_idGROUP BY teachers.name ORDER BY n\_reviews ASC ```
Esta es mi solución: `SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviewsFROM teachersINNER JOIN courses ON teachers.id = courses.teacher_idGROUP BY teacherORDER BY total_reviews DESC`;
SELECT teachers.name AS teacher, SUM(courses.n\_reviews) AS total\_reviewsFROM teachersINNER JOIN courses ON teachers.id = courses.teacher\_id--WHERE courses.n\_reviews > 0GROUP BY teacherORDER BY total\_reviews DESC;
Mi aporte: `SELECT teachers.name As teacher, SUM(courses.n_reviews) As total_reviewsFROM teachersINNER JOIN courses ON teachers.id = courses.teacher_idGROUP BY teachers.idHAVING total_reviews > 0ORDER BY total_reviews DESC`
![](https://static.platzi.com/media/user_upload/image-de0a7ebc-8a04-4405-9098-47bf770c58f2.jpg)
Mi primer intento, no pensé que había cursos sin profesor, me sorprendió XD ![](https://static.platzi.com/media/user_upload/image-69b6e665-4a64-48e6-8922-115f8af766e7.jpg) Este otro es con Inner Join. (Que está bien)![](https://static.platzi.com/media/user_upload/image-56865f43-bf5b-443b-b98f-16f75391df0b.jpg)
Aquí mi solución, sentí pánico cuando me di cuenta que tenía que usar el JOIN xD ```js SELECT teachers.name AS teacher, SUM(n_reviews) AS total_reviews FROM courses LEFT JOIN teachers ON courses.teacher_id = teachers.id GROUP BY teacher_id HAVING teacher_id IS NOT NULL ORDER BY total_reviews DESC ; ```
Aquí mi solución, sentí pánico cuando me di cuenta que tenía que usar el JOIN xD `SELECT teachers.name AS teacher, SUM(n_reviews) AS total_reviews FROM coursesLEFT JOIN teachers ON courses.teacher_id = teachers.idGROUP BY teacher_idHAVING teacher_id IS NOT NULLORDER BY total_reviews DESC;`
**Solucion:** ```js -- Escribe tu código aquí 👇 SELECT t.name AS teacher, SUM(c.n_reviews) AS total_reviews FROM courses c INNER JOIN teachers t ON c.teacher_id=t.id GROUP BY t.name ORDER BY total_reviews DESC ```-- Escribe tu código aquí 👇SELECT t.name AS teacher, SUM(c.n\_reviews) AS total\_reviewsFROM courses c INNER JOIN teachers t ON c.teacher\_id=t.idGROUP BY t.nameORDER BY total\_reviews DESC
![](https://static.platzi.com/media/user_upload/image-9424edaa-dae2-48f0-a0e4-2dbc297b2c51.jpg)
reto completado ```js SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviews FROM courses INNER JOIN teachers ON teachers.id = courses.teacher_id GROUP BY teacher ORDER BY total_reviews DESC; ```
![](https://static.platzi.com/media/user_upload/image-d077beda-2723-4c79-b07f-efc134ded514.jpg) Mi query: SELECT teachers.name AS teacher,SUM(courses.n\_reviews) total\_reviews FROM courses INNER JOIN teachers ON courses.teacher\_id = teachers.id GROUP BY teacher ORDER BY total\_reviews DESC ;
Les dejo mi query: SELECT t.name AS teacher, SUM(c.n\_reviews) AS total\_reviews FROM teachers t INNER JOIN courses c on t.id = c.teacher\_id WHERE c.n\_reviews != 0 GROUP BY teacher ORDER BY total\_reviews DESC;
```` \-- Escribe tu código aquí 👇SELECTteachers.name AS teacher,SUM(courses.n\_reviews) AS total\_reviewsFROM teachersINNER JOIN coursesON teachers.id = courses.teacher\_idGROUP BY teacherHAVING courses.teacher\_id IS NOT NULLORDER BY total\_reviews DESC; ````
Aqui mi solucion..... . . . . . . . . ```js SELECT teachers.name as teacher, sum(courses.n_reviews) as total_reviews FROM courses INNER JOIN teachers ON courses.teacher_id = teachers.id group by teacher having total_reviews > 0 order by total_reviews Desc; ```
```js SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviews FROM teachers INNER JOIN courses ON teachers.id = courses.teacher_id GROUP BY teacher HAVING total_reviews > 1 ORDER BY total_reviews DESC; ```SELECT  teachers.name AS teacher,  SUM(courses.n\_reviews) AS total\_reviewsFROM teachersINNER JOIN coursesON teachers.id = courses.teacher\_idGROUP BY teacherHAVING total\_reviews > 1ORDER BY total\_reviews DESC;
![](https://static.platzi.com/media/user_upload/image-f2018afd-4f90-4489-8d0e-6462b8b5333a.jpg)
```js SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviews FROM courses INNER JOIN teachers ON courses.teacher_id = teachers.id GROUP BY courses.teacher_id, teachers.name ORDER BY total_reviews DESC; ```
select b.name as teacher,sum(a.n\_reviews) as total\_reviewsFROM courses AS A LEFT JOIN teachers AS BON a.teacher\_id =b.idgroup by b.namehaving b.name is not nullorder by total\_reviews desc
SELECT a.name AS teacher, SUM(b.n\_reviews) AS total\_reviewsFROM teachers as aINNER JOIN courses as bON a.id = b.teacher\_idGROUP BY teacherORDER BY total\_reviews DESC;
```js SELECT SUM(n_reviews) AS total_reviews, teachers.name AS teacher FROM courses  RIGHT JOIN teachers ON teacher_id = teachers.id GROUP BY teacher HAVING total_reviews >= 1 ORDER BY total_reviews DESC; ```
SELECT teachers.name AS teacher, SUM(courses.n\_reviews) AS total\_reviews FROM teachers INNER JOIN courses ON teachers.id = courses.teacher\_id GROUP BY teacher ORDER BY total\_reviews DESC;
Los retos comienzan a ponerse buenos! ![](https://static.platzi.com/media/user_upload/image-1e729ae5-3946-43fb-a732-ba4cd7486e10.jpg)
Comparto mi solución. SELECT  teachers.name AS teacher,  SUM( courses.n\_reviews) AS total\_reviews FROM courses INNER JOIN teachers ON courses.teacher\_id = teachers.id  GROUP BY teacher ORDER BY total\_reviews DESC;
Así quedo mi solución, me costó, pero pude hacerlo sin ayuda. ```js SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviews FROM courses INNER JOIN teachers ON courses.teacher_id = teachers.id GROUP BY teacher HAVING courses.n_reviews >= 1 ORDER BY total_reviews DESC; ```SELECT teachers.name AS teacher, SUM(courses.n\_reviews) AS total\_reviews FROM courses INNER JOIN teachers ON courses.teacher\_id = teachers.id GROUP BY teacher HAVING courses.n\_reviews >= 1 ORDER BY total\_reviews DESC;

Hola, les comparto mi solución!

SELECT
  teachers.name AS teacher,
  SUM(courses.n_reviews) AS total_reviews
FROM courses
INNER JOIN teachers
  ON courses.teacher_id = teachers.id
GROUP BY teacher
ORDER BY total_reviews DESC;
Mi solución ```js SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviews FROM teachers INNER JOIN courses ON teachers.id = courses.teacher_id WHERE teacher_id IS NOT NULL GROUP BY teacher HAVING total_reviews >= 1 ORDER BY total_reviews DESC ```-- Escribe tu código aquí 👇 SELECT teachers.name AS teacher, SUM(courses.n\_reviews) AS total\_reviewsFROM teachersINNER JOIN coursesON teachers.id = courses.teacher\_idWHERE teacher\_id IS NOT NULLGROUP BY teacherHAVING total\_reviews >= 1ORDER BY total\_reviews DESC
Aqui va mi solucion: `SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviewsFROM teachersINNER JOIN courses ON teachers.id = courses.teacher_idGROUP BY teacherHAVING total_reviews >=1ORDER BY total_reviews DESC;`
Mi solución ```css SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviews FROM teachers LEFT JOIN courses ON courses.teacher_id = teachers.id WHERE courses.name IS NOT NULL GROUP BY teachers.name ORDER BY total_reviews DESC; ```
SELECT teachers.name as teacher, Sum(courses.n_reviews) as total_reviews 
from teachers 
inner join courses on teachers.id = courses.teacher_id
group by teacher 
order by total_reviews desc;

![](https://static.platzi.com/media/user_upload/image-1a74cc89-0c78-4b1e-85c3-adcdd181dd5c.jpg)
SUPER... ![](https://static.platzi.com/media/user_upload/image-4f3439c1-cbcb-425d-be7a-2724334b74e8.jpg)
Desglosare la solucion, que me parecio acertada SELECT teachers.name AS teacher, SUM(courses.n\_reviews) AS total\_reviews FROM teachers INNER JOIN courses ON teachers.id = courses.teacher\_id GROUP BY teacher ORDER BY total\_reviews DESC; Especificamos la tabla name de teachers, y le asignamos el alias de teacher, ahi cumplimos un objetivo del reto Hacemos la suma, especificando que la suma se realice desde la tabla courses con la columa n\_reviews y dandole el alias de total reviews Esta selección la hacemos desde teachers Despues desde la tabla teachers, hacemos la union Esta union consiste en tomar los id que en la tabla teachers y la columna id, sea coincidente con los de tabla courses en la columna teacher\_id Y como es una union INNER JOIN, esta nos condiciona a que se incluyan en el resultado profesores que tengan cursos, los que no, son descartados Posteriormente al agrupar los datos con GROUP BY teachers Agrupamos en un resultado teacher, aunque el profesor se repita, solo se mostrara una sola vez, junto con su respectiva suma Algo a destacar y que aprendi es la automatizacion del GROUP BY La base de datos entiende automáticamente que la suma se debe calcular para cada conjunto de filas que comparten el mismo valor en la columna `teacher`. No necesitas hacer nada adicional para asignar las sumas a cada nombre de profesor; la base de datos realiza este proceso automáticamente según la lógica de la consulta SQL. La base de datos al encontrar los teachers, automaticamente asigna los resultados, que ya se han sumado con SUM por la agrupacion, sigo sin entenderlo claramente, pero tal vez pueda saber mas con cursos avanzados Asi es como podemos asignar las columnas, teacher por la agrupacion de resultados, y el total\_reviews como consecuencia de sumar todas las reviews junto con el id de los teachers Cualquier correccion es bienvenida
Mi solucion ![](https://static.platzi.com/media/user_upload/image-78021fbf-c6e2-4a4b-8c00-5a96b9a6c945.jpg)
SELECT teachers.name AS teacher, SUM(n_reviews) AS total_reviews
FROM courses
INNER JOIN teachers ON teacher_id = teachers.id
GROUP BY teacher
HAVING total_reviews > 0
ORDER BY total_reviews DESC;
No recuerdo que hayamos visto la función SUM() en el curso, igual la usé, era la única forma de resolver esto (que yo encontré, seguramente hay más). `SELECT teachers.name as teacher, SUM(courses.n_reviews) AS total_reviewsFROM teachers  INNER JOIN courses ON teachers.id = courses.teacher_id  GROUP BY teacher  ORDER BY total_reviews DESC;`
Esta fue mi respuesta En los comentarios veo que muchos utilizaron inner ```js SELECT t.name AS teacher, SUM(c.n_reviews) AS total_reviews FROM teachers t left JOIN courses c ON t.id = c.teacher_id GROUP BY teacher having total_reviews > 0 ORDER BY total_reviews DESC; ```
SELECT t.name AS teacher, SUM(c.n\_reviews) AS total\_reviews FROM teachers t INNER JOIN courses c ON t.id = c.teacher\_id GROUP BY t.id, t.name ORDER BY total\_reviews DESC;

MI SOLUCION CON SU AYUDA ( ’ o ’ )

SELECT 
  teachers.name AS teacher, 
  SUM(courses.n_reviews) AS total_reviews 
FROM teachers
INNER JOIN courses 
  ON teachers.id = courses.teacher_id
GROUP BY teacher
ORDER BY total_reviews DESC;
SELECT teachers.name AS teacher, SUM(courses.n\_reviews) AS total\_reviews FROM teachers RIGHT JOIN courses ON teachers.id = courses.teacher\_id WHERE teacher\_id IS NOT NULL GROUP BY teacher ORDER BY total\_reviews DESC; (tambien se puede resolver sin el WHERE y poniendo INNER JOIN)
![](https://static.platzi.com/media/user_upload/image-9aed095b-6f49-46af-930d-b028c200cc8a.jpg) Completado
![](https://static.platzi.com/media/user_upload/image-2a42eab6-d416-4f52-b44a-d76933aa1036.jpg)
Mi solución 😎 ```txt SELECT teachers.name AS teacher, SUM (n_reviews) AS total_reviews FROM teachers INNER JOIN courses ON teachers.id = courses.teacher_id GROUP BY teacher ORDER BY total_reviews DESC ; ```SELECT   teachers.name AS teacher,  SUM (n\_reviews) AS total\_reviewsFROM teachersINNER JOIN courses ON teachers.id = courses.teacher\_idGROUP BY teacherORDER BY total\_reviews DESC;
`SELECT teachers.name AS teacher, SUM(n_reviews) AS total_reviewsFROM coursesLEFT JOIN teachers ON courses.teacher_id = teachers.id GROUP BY teacherHAVING teacher IS NOT NULLORDER BY total_reviews DESC;`
 cláusula JOIN, la función SUM y la cláusula GROUP BY

para agrupar los cursos por profesor y luego sumar la cantidad total de reviews de los cursos de cada profesor. Luego, ordenarás los resultados de manera descendente. Aquí está la consulta SQL para lograrlo

Para tener encuenta, diferencias entre SUM y COUNT. SUM: Suma el valor obtenido del campo requerido (El campo debe ser valor número, decimal...). COUNT: Suma la cantidad de regitros.

Estuvo interesante el reto!

SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviews
FROM teachers
INNER JOIN courses 
ON teachers.id = courses.teacher_id
GROUP BY courses.teacher_id
HAVING total_reviews > 1
ORDER BY total_reviews DESC;
```js SELECT t.name AS teacher, SUM(n_reviews) AS total_reviews FROM teachers as t INNER JOIN courses as c ON t.id=c.teacher_id GROUP BY teacher_id ORDER BY total_reviews DESC; ```Yo lo hice asi

Medio confuso, pero se logró:

SELECT 
  t.name as teacher,
  SUM(n_reviews) AS total_reviews
FROM courses c

LEFT JOIN teachers t ON c.teacher_id = t.id

WHERE t.name IS NOT NULL

GROUP BY t.name

ORDER BY total_reviews DESC;
```txt SELECT teachers.name as teacher, SUM(courses.n_reviews) AS total_reviews FROM courses INNER JOIN teachers ON teachers.id=courses.teacher_id GROUP BY teachers.name HAVING total_reviews > 0 ORDER BY total_reviews DESC ; ```Experimentando me di cuenta que el orden que hagas en el Inner Join no es determinante, ya sea que traigas primero la tabla "teachers" y luego lo unas con "courses" a través del FK, o lo hagas al reves. Y de igual forma, al declarar a través de que llave se hará la unión no es determinante si se coloca primero la llave "teachers.id" o la de "courses.teacher\_id". Les dejo por acá un ejemplo de lo que me refiero, el resultado es el mismo.```txt SELECT teachers.name as teacher, SUM(courses.n_reviews) AS total_reviews FROM teachers INNER JOIN courses ON courses.teacher_id=teachers.id GROUP BY teachers.name HAVING total_reviews > 0 ORDER BY total_reviews DESC ; ```
El having puede estar de demás pero le da mas solidez![](https://static.platzi.com/media/user_upload/imagen-9bc8f413-ef80-475c-b9c9-34bd79e032e9.jpg)

Perdí una vida pero lo logré, jaja

select c.teacher_id,c.name
from courses c
order by c.teacher_id

Asi se fue XD

SELECT teachers.name AS teacher, sum(courses.n_reviews) AS total_reviews
FROM teachers,courses
WHERE teachers.id = courses.teacher_id 
GROUP BY teacher
ORDER BY total_reviews DESC
;
SELECT t.name AS teacher, sum(c.n_reviews) AS total_reviews
FROM teachers AS t, courses AS c 
WHERE t.id = c.teacher_id
GROUP BY teacher
ORDER BY total_reviews desc;

buena practica

SELECT
  teachers.name AS teacher, 
  sum(n_reviews) AS total_reviews
FROM
  courses
INNER JOIN 
  teachers ON courses.teacher_id=teachers.id  
GROUP BY
  teacher_id
ORDER BY
  total_reviews DESC
;

Comparto mi solución, el query funciona si omito el WHERE Y HAVING, pero decido dejarlo así por las condiciones que pide el ejercicio 😃

SELECT teachers.name AS teacher, SUM(n_reviews) AS total_reviews FROM courses
INNER JOIN teachers ON courses.teacher_id = teachers.id
WHERE courses.teacher_id IS NOT NULL
GROUP BY courses.teacher_id
HAVING total_reviews > 1
ORDER BY total_reviews DESC;

Aquí mi aporte con LEFT JOIN
.
.
.
.
.
.
.

SELECT t.name AS teacher,
SUM(c.n_reviews) AS total_reviews
FROM courses AS c
LEFT JOIN teachers AS t
ON c.teacher_id = t.id
WHERE t.id IS NOT NULL
GROUP BY teacher
ORDER BY total_reviews DESC
;

mi aporte

SELECT 

teachers.name AS teacher,

SUM(n_reviews) AS total_reviews

FROM courses
LEFT JOIN teachers ON courses.teacher_id = teachers.id

WHERE teacher_id IS NOT NULL

GROUP BY teacher
ORDER BY total_reviews DESC;

SELECT
teachers. name AS teacher ,
SUM(courses. n_reviews) AS total_reviews
FROM teachers
INNER JOIN courses
ON teachers. id = courses.teacher_id
GROUP BY teacher
ORDER BY total_reviews DESC

Buenas tardes muchachos acá están mis aportes

<SELECT 
teachers.name AS teacher,
SUM (courses.n_reviews) AS total_reviews
FROM teachers
INNER JOIN courses ON teachers.id = courses.teacher_id
GROUP BY teacher_id
ORDER BY Total_reviews DESC;> 
SELECT teachers.name AS teacher, SUM(courses.n_reviews) AS total_reviews FROM teachers
INNER JOIN courses ON teachers.id = courses.teacher_id
GROUP BY teachers.id
ORDER BY total_reviews DESC;

Con lucha pero se pudo

SELECT teachers.name AS teacher,SUM(n_reviews) AS total_reviews
FROM courses 
LEFT JOIN teachers ON teacher_id = teachers.id
GROUP BY teacher_id HAVING teacher_id is not null
ORDER BY total_reviews DESC;

Aqui mi propuesta de solucion, me llama la atencion como en las demas propuestas de solucion los compañeros hacen el join desde teachers como tabla de la cual jalan la informacion
Segun a mi me enseñaron en un join debes poner tu from desde la tabla donde esté la segunda tabla como foranea, o bien la tabla en donde este contenida la informacion de varias tablas, para despues poder explotar correctamente las relaciones, digo en esta ocasión no importa mucho pero me pareció muy curioso que colocaran el from desde una tabla independiente y no de la tabla donde estan enlazadas ambas

.
.
.
.
.
.
.
.
.
.

SELECT t.name AS teacher, SUM(c.n_reviews) AS total_reviews
FROM teachers t
INNER JOIN courses c ON t.id = c.teacher_id
WHERE c.n_reviews > 0
GROUP BY t.id, t.name
ORDER BY total_reviews DESC;

SELECT teachers.id, teachers.name AS teacher, SUM(courses.n_reviews) AS    total_reviews
  FROM teachers
  LEFT JOIN courses ON teachers.id = courses.teacher_id
  GROUP BY courses.teacher_id
  HAVING total_reviews > 0
  ORDER BY total_reviews DESC;

Hola les comparto mi query, ojo que no está bien, en mi caso no leí la parte de no contemplar los cursos sin review y tampoco renombre la columna t. name

<


SELECT t.name, sum(c.n_reviews) as total_reviews
FROM teachers t 
left JOIN courses c
ON t.id = c.teacher_id
Group by t.name
Order by total_reviews desc
;  
>

Aquí el correcto:

<

SELECT t.name as tracher, sum(c.n_reviews) as total_reviews
FROM teachers t 
left JOIN courses c
ON t.id = c.teacher_id
WHERE c.teacher_id IS NOT NULL
Group by t.name
Order by total_reviews desc
; 


> 

Aquí mi aporte a la solución:

SELECT
  T.name as teacher,
  SUM(C.n_reviews) AS total_reviews
FROM teachers AS T
INNER JOIN courses AS C
ON T.id = C.teacher_id
GROUP BY teacher
ORDER BY total_reviews DESC
;

Mi solucion









SELECT teachers.name AS teacher, 
SUM(n_reviews) AS total_reviews
FROM courses
INNER JOIN teachers ON courses.teacher_id = teachers.id
WHERE teacher_id IS NOT NULL
GROUP BY teacher_id
ORDER BY total_reviews DESC
;
-- Escribe tu código aquí 👇
SELECT teachers.name AS teacher, SUM(n_reviews) AS total_reviews
FROM courses
RIGHT JOIN teachers on teachers."id" = courses.teacher_id
GROUP BY teachers.name
HAVING total_reviews > 0
ORDER BY total_reviews DESC

mi solucion:

<SELECT teachers.name as teacher,sum(courses.n_reviews) as total_reviews FROM courses INNER JOIN teachers
on teachers.id=courses.teacher_id
where courses.teacher_id  is not null
and courses.n_reviews>=1
group by teacher
order by total_reviews DESC> 
undefined