Let's say we have a table 'Food_Request' that contains the following values:
Name | Food | Date |
---|---|---|
John | Egg | 7/1 |
Meg | Egg | 7/10 |
Sue | Egg | 7/5 |
John | Salad | 6/10 |
Meg | Cheese | 6/20 |
Sue | Salad | 6/25 |
I'm trying to create a query that returns the name that meet the following conditions:
Someone ordered a salad FIRST, then the immediate following order from the same person is an Egg.
I've been trying to use the lag function to select the previous row of the customer's name, but I don't think I'm getting the correct results. Here's what I have so far:
Select Name
from (select Name, Date, Food, case when Food = 'Egg' and lag(Food) over (order by name, date asc) = 'Salad' then 1 else 0 as Prev_Order from Food_Request) table1
where Prev_Order = 1
The desired result should be Sue and John.
Thank you!