PARTITION & ORDER
Parte de la sección Fundamentos del Journey de SQL de Coddy — lección 60 de 72.
También podemos combinar PARTITION BY con ORDER BY. Por ejemplo, considere la siguiente table1:
| 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 numerará las filas en orden ascendente por el id de cada tipo:
| id | type | row_num |
| 132 | t1 | 2 |
| 52 | t2 | 1 |
| 92 | t1 | 1 |
| 154 | t3 | 1 |
| 198 | t1 | 3 |
Ahora, el id 132 tiene row_num 2 porque es mayor que 92 y menor que 198 (de todas las filas de tipo t1).
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>
Escribe una consulta SQL para analizar la secuencia de colores de puertas dentro de cada país, ordenada por año de publicación. Para cada puerta, muestra:
- El país
- El color
- El año de publicación
- Un número que representa el orden de colores dentro de cada país basado en el año de publicación. Llama a esta columna
color_sequence_number
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