I have a situation that I would like to resolve in SQL using as few inner joins as possible, so I am thinking of using window functions.
I am using Snowflake, but I am happy to see answers in other DB engines as well.
Table sales has sale_id and seller_id, as well as sale_datetime, amount... Table seller has seller_id
I would like to get the first and second sales for each seller, as columns preferably (so that I can add and subtract eg sum of amounts). If there is only one sale, ideally I would not retrieve it.
I am trying to use something like this:
select se.seller_id,sa.*, first_value(sale_datetime) over (ORDER BY
sale_datetime ), LAG(sale_datetime) OVER (ORDER BY sale_datetime)
from seller se inner join sales sa on sa.seller_id = se.seller_id
order by se.seller_id;
But I would need to add a group by, because the window functions need to be applied at the seller level, not to the total of the table. Whether I add it at the end of the query or inside the window, I get an error.
The other way that I have of doing this without windows is with two with...as clauses that retrieve first and second sale for each seller respectively and a join between them, but I am trying to avoid this for performance reasons.
Thanks!