Reputation: 99
I have a table with articles, Day Date, and amount of bought. I want a reslut table where I can see the amount off all Articles and how many where bought and the amount they where bought at the unknown date before:
Example result of:
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|
|------------|---------|----------|
The result should look like:
|------------|---------|----------|----------|----------|
| 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| | |
|------------|---------|----------|----------|----------|
Is this anyway possibile to do?
Best Zio
Upvotes: 1
Views: 50
Reputation: 222432
You want 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
Upvotes: 1