PARTITION BY criterion
Coddy SQL 여정의 기초 섹션에 포함된 레슨 — 72개 중 59번째.
OVER () 절의 또 다른 옵션은 PARTITION BY입니다
이는 각 그룹에 대해 행을 별도로 번호 매기는 것을 허용합니다
예를 들어:
| 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 table1이것은 각 타입 내에서 자체적으로 번호를 매기는 열을 생성합니다:
| id | type | row_num |
| 132 | t1 | 1 |
| 52 | t2 | 1 |
| 92 | t1 | 2 |
| 154 | t3 | 1 |
| 198 | t1 | 3 |
id 92는 row_num 2를 가지는데, 이는 type t1을 id로 정렬했을 때 두 번째 행이기 때문입니다.
참고: ROW_NUMBER()는 OVER() 내의 ORDER BY 절을 필요로 하며, 이를 통해 각 파티션 내에서 행이 어떻게 번호가 매겨질지를 결정합니다.
심지어 PARTITION BY 내부에 여러 열을 지정할 수도 있습니다:
ROW_NUMBER() OVER (PARTITION BY type, hue ORDER BY id)챌린지
쉬움사용 가능한 테이블 및 열:
<strong>doors</strong>:<strong>id</strong>,<strong>publication_year</strong><strong>doors_specs</strong>:<strong>id</strong>,<strong>country</strong>,<strong>color</strong>
공장이 문을 제작하고 있습니다. publication_year가 2000보다 작은 각 country와 color 조합에 대해 문에 번호를 매겨야 합니다. 이 열의 이름을 row_num으로 지정하세요.
각 그룹 내에서 해당 문의 id에 대한 오름차순으로 문을 번호 매겨야 합니다. 사양이 없는 문은 무시하세요. 최종 결과를 id에 대한 오름차순으로 정렬하세요.
치트 시트
PARTITION BY를 OVER() 절에서 사용하여 그룹 내 행을 번호 매기세요:
SELECT id, type, ROW_NUMBER() OVER (PARTITION BY type) as row_num
FROM table1여러 열로 파티션할 수 있습니다:
ROW_NUMBER() OVER (PARTITION BY type, hue)직접 해보기
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
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