我有一张桌子,上面有文章,日期和购买金额。我想要一个reslut表,从中可以查看所有商品的金额以及在未知日期之前购买的数量和购买的数量:
示例结果:
select articleid, amount, date from table1 where articleid in(7,8)
|------------|---------|----------|
| articleid | amount | date |
|------------|---------|----------|
| 7 | 34 |20.10.2019|
|------------|---------|----------|
| 7 | 2 |15.10.2019|
|------------|---------|----------|
| 8 | 12 |13.10.2019|
|------------|---------|----------|
| 8 | 35 |15.09.2019|
|------------|---------|----------|
结果应类似于:
|------------|---------|----------|----------|----------|
| articleid | amount | date |prev date |prevamount|
|------------|---------|----------|----------|----------|
| 7 | 34 |20.10.2019|15.10.2019| 2 |
|------------|---------|----------|----------|----------|
| 7 | 2 |15.10.2019| | |
|------------|---------|----------|----------|----------|
| 8 | 12 |13.10.2019|15.09.2019| 35 |
|------------|---------|----------|----------|----------|
| 8 | 35 |15.09.2019| | |
|------------|---------|----------|----------|----------|
反正这有可能吗?
最佳Zio
您要lag()
:
select
articleid,
amount,
date,
lag(date) over(partition by articleid order by date) prevdate,
lag(amount) over(partition by articleid order by date) prevamount
from table1
order by articleid, date desc