简体   繁体   中英

SQL value of previous (unknown) date

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM