I have the following table called fruits:
id  fruit_bought   quantity   date
1 | orange       | 100      | 2018-01-10
2 | apple        | 50       | 2018-02-05
3 | orange       | 75       | 2018-03-07
4 | orange       | 200      | 2018-03-15
5 | apple        | 10       | 2018-03-17
6 | orange       | 20       | 2018-03-20
I want to return rows that have fruit_bought of orange if any time in the previous 10 days any oranges were bought, starting with the date 2018-03-20 (row with id 6).
For example:
- Starting at 2018-03-20, there was a purchase of oranges on this date (rowid 6)
- Was there any orange purchases 10 days prior from this? Yes: on '2018-03-15' (row id 4)
- Was there any orange purchases 10 days prior from this date? Yes: on '2018-03-07' (row id 3)
- Was there any orange purchases 10 days prior from this date? No.
In the end, the query I'm trying to create would return the rows with the id of 3, 4, and 6 (but not 1).
The query I have so far is the following:
SELECT *, LAG(date, 1) OVER (PARTITION BY fruit_bought) FROM fruits
WHERE fruit_bought = 'orange';
This returns every row where fruit_bought is orange, and it adds an additional lag column.
 
     
     
     
    