很抱歉为标题混淆,我不确定该如何措辞。
下面是我的数据集:
+----+-----------------------------+--------+
| Id | Date | Amount |
+----+-----------------------------+--------+
| 1 | 2019-02-01 12:14:08.8056282 | 10 |
| 1 | 2019-02-04 15:23:21.3258719 | 10 |
| 1 | 2019-02-06 17:29:16.9267440 | 15 |
| 1 | 2019-02-08 14:18:14.9710497 | 10 |
+----+-----------------------------+--------+
这是银行尝试从债务人收取钱款的一个示例,在这种情况下,首先尝试收取欠款的10%,如果设法对卡进行收费,则尝试收取15%,如果这笔费用会错误(例如资金不足),则再次尝试10%。
所需的输出将是:
+----+--------+---------+
| Id | Amount | Attempt |
+----+--------+---------+
| 1 | 10 | 1 |
| 1 | 15 | 2 |
| 1 | 10 | 3 |
+----+--------+---------+
我尝试过:
SELECT Id, Amount
FROM table1
GROUP BY Id, Amount
我正在努力根据Amount列中值的更改时间来创建新列,因为我认为这可以用作另一个可解决此问题的分组变量。
答案 0 :(得分:2)
如果只想更改值,请使用lag()
:
select t.id, t.amount,
row_number() over (partition by id order by date) as attempt
from (select t.*, lag(amount) over (partition by id order by date) as prev_amount
from table1 t
) t
where prev_amount is null or prev_amount <> amount