我有两个表,第一个表包含交易明细,第二个表包含用户的订单:
id | transaction_date
1 | 2019-01-01
2 | 2019-02-01
3 | 2019-01-01
id | transaction_id | amount | user_id
15 1 7 1
20 2 15 1
25 3 25 1
我想得到这个结果,也就是说,对于所有用户,订单还具有他根据交易日期支付的先前金额。
user_id | amount | previous amount
1 7 NULL
1 15 7
1 25 15
我尝试了包括使用LAG函数在内的多种方法,但似乎无法实现,因为我必须加入另一个表才能获得transaction_date。我想我应该用左联接进行子查询,但我不知道如何只获得前一个订单
谢谢
这是join
和lag()
:
select t2.user_id, t2.amount,
lag(t2.amount) over (partition by t2.user_id order by t1.date) as prev_amount
from table1 t1 join
table2 t2
on t2.transaction_id = t1.id;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句