运行 总行数(按 ID)

Running total of rows by ID

我有一个 ID、交易和这些交易日期的列表。我想在每个 ID 中创建每个交易的计数。

我的起始 table 看起来像这样:

id  trxn_dt trxn_amt

1   10/31/2014  58

1   11/9/2014   34

1   12/10/2014  12

2   7/8/2014    78

2   11/20/2014  99

3   1/5/2014    120

4   2/17/2014   588

4   2/18/2014   8

4   3/9/2014    65

4   4/25/2014   74

我希望最终结果看起来像这样:

id  trxn_dt trxn_amt trxn_count

1   10/31/2014  58  1

1   11/9/2014   34  2

1   12/10/2014  12  3

2   7/8/2014    78  1

2   11/20/2014  99  2

3   1/5/2014    120 1

4   2/17/2014   588 1

4   2/18/2014   8   2

4   3/9/2014    65  3

4   4/25/2014   74  4

Count(distinct(id)) 只会给我不同 ID 的总数,而不是 运行 每个在每个新 ID 重新启动的 ID 的总数。

谢谢!

使用Row_number我们可以实现这个

    Select *,
ROW_NUMBER()OVER(PARTITION BY id ORDER BY (SELECT NULL))trxn_count
 from Transactions

SQL-Server中你可以在下面使用ROW_NUMBER:

SELECT id,
       trxn_dt,
       trxn_amt,
       ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Id, trxn_dt) AS trxn_count
FROM   StarningTable

MySQL中,您可以执行以下操作:

SELECT 
  t.id,
  t.trxn_dt,
  t.trxn_amt, 
  @cur:= IF(id=@id, @cur+1, 1) AS RowNumber, 
  @id := id 
FROM 
  StarningTable t 
CROSS JOIN 
    (SELECT @id:=(SELECT MIN(id) FROM StarningTable t), @cur:=0) AS init 
ORDER BY 
  t.id