【问题标题】:How can I get incrementing number for this table?我怎样才能得到这个表的递增数字?
【发布时间】:2021-03-30 18:50:43
【问题描述】:

这是我的事件表。如何编写查询以添加列 X 当它在事件列中遇到 1 时递增

输入:

|id    |event|
|------|-----|
|1     |0    |
|2     |0    |
|3     |1    |
|4     |0    |
|5     |1    |
|6     |0    |
|7     |0    |
|8     |0    |
|9     |1    |
|10    |0    |

预期输出:

|id    |event| X |
|------|-----|---|
|1     |0    | 1 |
|2     |0    | 1 |
|3     |1    | 2 |
|4     |0    | 2 |
|5     |1    | 3 |
|6     |0    | 3 |
|7     |0    | 3 |
|8     |0    | 3 |
|9     |1    | 4 |
|10    |0    | 4 |

【问题讨论】:

    标签: mysql sql select


    【解决方案1】:

    您只需要event 的累积总和:

    select t.*,
           (sum(event) over (order by id) + 1) as x
    from t;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多