如何逐步为每个组编号行

时间:2012-07-30 21:05:04

标签: mysql

对任何可以提供帮助的人,

我想在mysql中创建一个数据查询,以递增编号按事务ID分组的行,并在下一个事务ID上重新开始编号,依此类推。

这是我的数据样本:

transaction_id | run_index
--------------------------
1001           | 20
1001           | 25
1001           | 31
1001           | 40
1002           | 4
1002           | 11
1002           | 16
1002           | 21
1002           | 35
1003           | 07
1003           | 18
1003           | 44

我希望它看起来像这样:

transaction_id | run_index | run_order
--------------------------------------
1001           | 20        | 1
1001           | 25        | 2
1001           | 31        | 3
1001           | 40        | 4
1002           | 4         | 1
1002           | 11        | 2
1002           | 16        | 3
1002           | 21        | 4
1002           | 35        | 5
1003           | 7         | 1
1003           | 18        | 2
1003           | 44        | 3

这是针对数据分析的特殊报告。

2 个答案:

答案 0 :(得分:0)

SELECT transaction_id, run_index, 
    CASE WHEN @transaction_id != transaction_id THEN (@run := 1) - !(@transaction_id := transaction_id) ELSE @run := @run + 1 END AS run_order
FROM (  SELECT transaction_id, run_index
        FROM table_name, (SELECT @transaction_id := NULL, @run := NULL) AS var
        ORDER by transaction_id ASC, run_index DESC) AS h

应该是你想要的。

答案 1 :(得分:0)

SELECT transaction_id,
       run_index,
       IF(@CG=transaction_id, @I:=@I+1, @I:=1),
       @CG:=transaction_id AS run_order
FROM ...
INNER JOIN (SELECT @I:=0, @CG:=-1) x

示例结果集:

+---------+--------------------------------+--------------+
| feed_id | IF(@CG=feed_id,@I:=@I+1,@I:=1) | @CG:=feed_id |
+---------+--------------------------------+--------------+
|       8 |                              1 |            8 |
|       8 |                              2 |            8 |
|       8 |                              3 |            8 |
|      14 |                              1 |           14 |
|      14 |                              2 |           14 |
|      14 |                              3 |           14 |
|      14 |                              4 |           14 |
|      14 |                              5 |           14 |
|      14 |                              6 |           14 |
|      14 |                              7 |           14 |
+---------+--------------------------------+--------------+