Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

303
Views
Consulta SQL con Group, Order by y Random al mismo tiempo

No pude encontrar nada similar a este problema.

 CREATE TABLE IF NOT EXISTS `test` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `Nombre` varchar(50) COLLATE utf8_spanish2_ci DEFAULT NULL, `Orden` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci; INSERT INTO `test` (`Id`, `Nombre`, `Orden`) VALUES (1, 'Mark', NULL), (2, 'David', 1), (3, 'John', 1), (4, 'David', 2), (5, 'John', 3), (6, 'John', 2), (7, 'William', NULL);

Como vemos, John y David tienen más de una fila y hay una columna Ordenar, por lo que podemos ordenarla simplemente usando ORDENAR POR Nombre ASC, Ordenar ASC, pero esto no es exactamente lo que necesito.

ingrese la descripción de la imagen aquí

Aquí está el problema: me gustaría saber si es posible ordenar por nombre y hacer algún tipo de grupo para cada nombre, luego ordenar por Orden, y luego aplicar un ORDEN POR ALEATORIO() final para que siga viendo todos los filas de david, mark, john y William, pero en orden aleatorio.

ingrese la descripción de la imagen aquí

Entonces, cada vez que ejecuta la consulta, el orden es completamente aleatorio pero aún con algo de orden.

ingrese la descripción de la imagen aquí

Aquí hay un violín http://sqlfiddle.com/#!9/038bd7/7

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

esta consulta:

 select Nombre, rand() rnd from test group by Nombre

devuelve un número aleatorio para cada nombre único en la tabla.
Únalo a la tabla y ordene primero por ese número aleatorio y luego por Orden :

 select t.* from test t inner join (select Nombre, rand() rnd from test group by Nombre) r on r.Nombre = t.Nombre order by r.rnd, t.Orden

Ver la demostración .
Resultados:

 > Id | Nombre | Orden > -: | :------ | ----: > 7 | William | null > 1 | Mark | null > 2 | David | 1 > 4 | David | 2 > 3 | John | 1 > 6 | John | 2 > 5 | John | 3 > Id | Nombre | Orden > -: | :------ | ----: > 2 | David | 1 > 4 | David | 2 > 3 | John | 1 > 6 | John | 2 > 5 | John | 3 > 1 | Mark | null > 7 | William | null > Id | Nombre | Orden > -: | :------ | ----: > 2 | David | 1 > 4 | David | 2 > 1 | Mark | null > 7 | William | null > 3 | John | 1 > 6 | John | 2 > 5 | John | 3
over 4 years ago · Santiago Trujillo Report

0

Hm, realmente pensé que esto funcionaría, pero parece que no. Lo estoy publicando de todos modos, en caso de que inspire a otros...

 select * from test order by field(nombre, (select group_concat(distinct concat('\'',nombre,'\'') order by rand()) from test) );

Esto parece funcionar...

 select @i:= group_concat(distinct nombre order by rand()) from test; select *,find_in_set(nombre,@i) n from test order by n,orden
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!