Contar valores distintos en MySQL

Preet Sanghavi 20 enero 2022
Contar valores distintos en MySQL

En este tutorial, presentaremos diferentes métodos para contar valores distintos.

El método COUNT() en MySQL da el número total de filas en la tabla como salida. Sin embargo, en este artículo, estamos interesados ​​en comprender cómo calcular o contar el número de ocurrencias distintas de una expresión. La sintaxis para realizar esta operación se puede escribir como COUNT(DISTINCT expression). Este comando nos da el número total de valores distintos no nulos como resultado de la expresión particular.

Veamos este método en acción.

Sin embargo, antes de comenzar, creamos un conjunto de datos ficticio para trabajar. Aquí creamos una tabla, student_details, junto con algunas filas en ella.

-- create the table student_details
CREATE TABLE student_details(
  stu_id int,
  stu_firstName varchar(255) DEFAULT NULL,
  stu_lastName varchar(255) DEFAULT NULL,
  primary key(stu_id)
);
-- insert rows to the table student_details
INSERT INTO student_details(stu_id,stu_firstName,stu_lastName) 
 VALUES(1,"Preet","Sanghavi"),
 (2,"Rich","John"),
 (3,"Veron","Brow"),
 (4,"Geo","Jos"),
 (5,"Hash","Shah"),
 (6,"Sachin","Parker"),
 (7,"David","Miller");

La consulta anterior crea una tabla junto con filas con el nombre y apellido del estudiante. Para ver las entradas en los datos, usamos el siguiente código:

SELECT * FROM student_details;

El código anterior daría el siguiente resultado.

stu_id	stu_firstName	stu_lastName
1	      Preet	        Sanghavi
2	      Rich	        John
3	      Veron	        Brow
4	      Geo	        Jos
5	      Hash	        Shah
6	      Sachin	    Parker
7	      David	        Miller

Contar valores distintos en MySQL

La función COUNT (DISTINCT expression) de MySQL, como se indicó anteriormente, nos da el recuento de filas con valores únicos no nulos. Para contar el número de estudiantes con nombres únicos, usamos el siguiente código.

-- Count the number of students with different first names
SELECT COUNT(DISTINCT stu_firstName) as distinct_first_names FROM student_details ;

El código anterior cuenta el número de nombres distintos de la tabla student_details. El resultado del código anterior es el siguiente.

distinct_first_names
7

Por lo tanto, podemos ver que los nombres únicos (Preet, Rich, Veron, Geo, Hash, Sachin y David) se han contado para generar el recuento final como 7.

Nota: En el código anterior, usamos el alias distinct_first_names con la palabra clave AS en MySQL.

Preet Sanghavi avatar Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn GitHub