I have a SQL database with a list of Customer IDs CustomerID
and invoices, the specific product purchased in each invoice ProductID
, the Date
and the Income
of each invoice . I need to write a query that will retrieve for each product, which was the second customer who made a purchase
How do I do that?
EDIT:
I have come up with the following query:
SELECT *, LEAD(CustomerID) OVER (ORDER BY ProductID, Date) AS 'Second Customer Who Made A Purchase' FROM a ORDER BY ProductID, Date ASC
However, this query presents multiple results for products that have more than two purchases. Can you advise?
Advertisement
Answer
I need to write a query that will retrieve for each product, which was the second customer who made a purchase
This sounds like a window function:
select a.* from (select a.*, row_number() over (partition by productid order by date asc) as seqnum from a ) a where seqnum = 2;