mysql中每组的行号 [英] Row number per group in mysql

查看:83
本文介绍了mysql中每组的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据这种情况生成查询结果,该查询结果可以根据crew_id和类型创建行号.

I want to produce query result base on this scenario that can create row number according to crew_id and type.

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

输出必须为ff:

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

我只想在此输出中使用一条select语句

I want a single select statement only in this output

推荐答案

问题已经很老了.但我想将其发布,以防有​​人遇到相同的问题.

The question is quite old. But I would like to post it in case someone will have a same problem.

首先,所描述的答案无法正确运行.例如,对于

First of all, described answers do not work correct. For example, for

id   crew_id   amount    type
1      4       1000      AUB
2      4       1500      AUB
5      5       1000      AUB
6      6       3000      AUB
8      6       3500      AUB
9      4       5000      AUB

(我刚刚删除了类型为'CA'的行),结果表将为

(I just removed rows with type 'CA') the result table will be

id   crew_id   amount    rank   type
1      4       1000      1      AUB
2      4       1500      2      AUB
9      4       5000      3      AUB
5      5       1000      4      AUB
6      6       3000      5      AUB
8      6       3500      6      AUB

因此,实际上它并没有同时使用crew_id和type,而只是使用type.

So in fact it doesn't use both crew_id and type, it just uses type.

这是我解决此问题的方法(可能有比使用两个嵌套的"CASE"更优雅的方法,但您明白了):

Here is how I solved this problem (probably there is a more elegant way to do it than use two nested 'CASE's, but you get the idea):

SELECT id,
    amount,
    CASE crew_id 
        WHEN @curCrewId THEN
            CASE type 
                WHEN @curType THEN @curRow := @curRow + 1 
                ELSE @curRow := 1
            END
        ELSE @curRow :=1
    END AS rank,
    @curCrewId := crew_id AS crew_id,
    @curType := type AS type
FROM Table1 p
JOIN (SELECT @curRow := 0, @curCrewId := 0, @curType := '') r
ORDER BY crew_id, type

主要思想仍然存在.我刚刚添加了一个变量@curCrewId.如果有人需要使用3个变量进行分组,则只需使用3个变量和3个嵌套的'CASE'. :)

The main idea remain. I just added a variable @curCrewId. If someone need to use 3 variables for grouping, so just use 3 variables and 3 nested 'CASE's. :)

这篇关于mysql中每组的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆