在MySQL 中按群組對行進行編號
考慮以下表格結構:
id | crew_id | amount | type |
---|---|---|---|
1 | 4 | 1000 | AUB |
2 | 4 | 1500 | AUB |
3 | 5 | 8000 | CA |
4 | 4 | 1000 | CA |
5 | 5 | 1000 | AUB |
6 | 6 | 3000 | AUB |
7 | 4 | 2000 | CA |
8 | 6 | 3500 | AUB |
9 | 4 | 5000 | AUB |
10 | 5 | 9000 | CA |
11 | 5 | 1000 | CA |
產生結果集包含crew_id和type的每個組合的行號,執行以下查詢:
SELECT id, crew_id, amount, type, ( CASE type WHEN @curType THEN @curRow := @curRow + 1 ELSE @curRow := 1 AND @curType := type END ) + 1 AS rank FROM Table1 p, (SELECT @curRow := 0, @curType := '') r ORDER BY crew_id,type asc;
解釋:
輸出:
id | crew_id | amount | type | row_number |
---|---|---|---|---|
1 | 4 | 1000 | AUB | 1 |
2 | 4 | 1500 | AUB | 2 |
9 | 4 | 5000 | AUB | 3 |
4 | 4 | 1000 | CA | 1 |
7 | 4 | 2000 | CA | 2 |
5 | 5 | 1000 | AUB | 1 |
3 | 5 | 8000 | CA | 1 |
10 | 5 | 9000 | CA | 2 |
11 | 5 | 1000 | CA | 3 |
6 | 6 | 3000 | AUB | 1 |
6 | 6 | 3000 | AUB | 2 |
以上是如何在 MySQL 中依群組對行進行編號?的詳細內容。更多資訊請關注PHP中文網其他相關文章!