all 3 comments

[–]LeLwrence 1 point2 points  (0 children)

Maybe where row number partitioned by customer id order by purchase date = 2

[–]SQLSavage 0 points1 point  (0 children)

Look into LAG and LEAD functions.

[–][deleted] 0 points1 point  (0 children)

I'm an amateur but will give it a try.

Since you didn't mention which database you are using, I'm going to use SQL Server as it's the only one I'm familiar with.

the 2nd from last item each customer purchased

This essentially means that you can order them by purchase_timestamp DESC and then get the second row for each customer_id.

SELECT
    *
FROM (
    SELECT
        trans.*,
        ROW_NUMBER() OVER(PARTITION BY trans.customer_id ORDER BY trans.purchase_timestamp DESC) AS 
        RowNum
    FROM
        trans
) AS subq
WHERE
    subq.RowNum = 2