3

I have a table that contains column Fruit,Date,Price,Flag.

I use First_value(Price) over (partition by Fruit order by Fruit, Date) to generate Column Price First

last_value(Price) over (partition by Fruit order by Fruit,Date rows between unbounded preceding and unbounded following) to generate Column Price Last

Fruit   Date       Price    Flag    Price first   Price Last
Apple   6/1/2015    1.4     Yes       1.4           1.9
Apple   6/2/2015    1.5     Yes       1.4           1.9
Apple   6/3/2015    2.5     Yes       1.4           1.9
Apple   6/4/2015    3       Yes       1.4           1.9
Apple   6/5/2015    1.7     Yes       1.4           1.9 
Apple   6/6/2015    1.9     No        1.4           1.9

But I need another column "Price Last Flag Yes" to give me the last updated price for fruit Apple that don't have flag No,In this case, it should be the price at 6/5/2015

Fruit   Date       Price    Flag    Price first  Price Last  Price Last Flag Yes
Apple   6/1/2015    1.4     Yes       1.4           1.9        1.7
Apple   6/2/2015    1.5     Yes       1.4           1.9        1.7
Apple   6/3/2015    2.5     Yes       1.4           1.9        1.7
Apple   6/4/2015    3       Yes       1.4           1.9        1.7
Apple   6/5/2015    1.7     Yes       1.4           1.9        1.7 
Apple   6/6/2015    1.9     No        1.4           1.9        1.7

I don't know how to query the condition that filters out the Flag "no" within the functions. I don't want to go through subqueries. It is possible to add conditions and filters within the function? Thanks

I don't want to use where clause because then I need to use subquery. I also tried last_value(case when Flag = 'Yes' then Price end) over (partition by fruit order by Fruit,date), it doesn't work either. For some reason it messes the data and some rows are empty.

1

1 Answer 1

2

There's the IGNORE NULLS option:

last_value(case when Flag = 'Yes' then Price end ignore nulls) 
over (partition by Fruit order by Date ...

Btw, partition by Fruit, Date order by Fruit,Date will not work, it's partition by Fruit order by Date instead

1
  • yeah thanks! that's what I need ---- ignore nulls. That way it works as a filter.
    – Sailormoon
    Jul 30, 2015 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.