I want to calculate the difference between first row with other rows in sql . I have a table named 'Trade' like
date | price |
---|---|
2013-01-01 | 70 |
2013-01-02 | 71 |
2013-01-03 | 72 |
2013-02-01 | 73 |
2013-02-02 | 74 |
2013-02-03 | 75 |
Expected Output:
date | price | first_value |
---|---|---|
2013-01-01 | 70 | NULL |
2013-01-02 | 71 | 1 |
2013-01-03 | 72 | 2 |
2013-02-01 | 73 | NULL |
2013-02-02 | 74 | 1 |
2013-02-03 | 75 | 2 |
I used this query:
select date,
price,
ABS(first_value(price) over (partition by date_trunc('month', date)) - price)
from trades;
But I get this output:
date | price | first_value |
---|---|---|
2013-01-01 | 70 | 0 |
2013-01-02 | 71 | 1 |
2013-01-03 | 72 | 2 |
2013-02-01 | 73 | 0 |
2013-02-02 | 74 | 1 |
2013-02-03 | 75 | 2 |
I would do it like this - check if we have the first value in a month, if so, then null
:
select
date,
price,
case when month = first_value(month) over (partition by date_trunc('month', date))
then null
else ABS(first_value(price) over (partition by date_trunc('month', date)) - price)
from trades;
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.