PARTITION BY criterion
Parte de la sección Fundamentos del Journey de SQL de Coddy — lección 59 de 72.
Otra opción para la cláusula OVER () es PARTITION BY
Nos permite numerar las filas para cada grupo por separado
Por ejemplo:
| id | type |
| 132 | t1 |
| 52 | t2 |
| 92 | t1 |
| 154 | t3 |
| 198 | t1 |
SELECT id, type, ROW_NUMBER() OVER (PARTITION BY type ORDER BY id) as row_num
FROM table1Esto generará una columna que numerará cada tipo dentro de sí misma:
| id | type | row_num |
| 132 | t1 | 1 |
| 52 | t2 | 1 |
| 92 | t1 | 2 |
| 154 | t3 | 1 |
| 198 | t1 | 3 |
id 92 tiene row_num 2 porque es la segunda fila de type t1 cuando se ordena por id.
Nota: ROW_NUMBER() requiere una ORDER BY cláusula dentro de la OVER() para determinar cómo se deben numerar las filas dentro de cada partición.
Incluso podemos especificar múltiples columnas dentro de PARTITION BY:
ROW_NUMBER() OVER (PARTITION BY type, hue ORDER BY id)Desafío
FácilTablas y columnas disponibles:
<strong>doors</strong>:<strong>id</strong>,<strong>publication_year</strong><strong>doors_specs</strong>:<strong>id</strong>,<strong>country</strong>,<strong>color</strong>
Una fábrica está fabricando puertas. Necesita numerar las puertas para cada combinación de country y color que tengan un publication_year menor que 2000. Nombra esta columna row_num.
Las puertas deben numerarse dentro de cada grupo en orden ascendente por su id. Las puertas sin especificaciones deben ignorarse. Ordena el resultado final en orden ascendente por el id.
Hoja de referencia
Utilice PARTITION BY en la cláusula OVER() para numerar filas dentro de grupos:
SELECT id, type, ROW_NUMBER() OVER (PARTITION BY type) as row_num
FROM table1Puede particionar por múltiples columnas:
ROW_NUMBER() OVER (PARTITION BY type, hue)Pruébalo tú mismo
Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.
Todas las lecciones de Fundamentos
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function8Statistics
Built-In Aggregate Part 1Built-In Aggregate Part 2Grouping Part 1Grouping Part 2Subqueries Part 1Subqueries Part 2Recap - Total Gain ShopRecap - Scooter ShopRecap - Coffee Shop11Window Functions part 1
ROW_NUMBER functionORDER BY criterionPARTITION BY criterionPARTITION & ORDERLEAD & LAG FunctionsRecap - LEAD & LAGRecap - PicturesRecap - Boxes3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns