Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding the earliest purchase place for each unique user based

I need to get the userID and the marketplace, where the user first bought something.

The db looks like this:

userID, marketplace, dateOfOrder
74526,  Amazon,      2/1/2021
74526,  eBay,        1/1/2021
74526,  Walmart,     12/10/2021 
74525,  Amazon,      14/5/2021
74525,  eBay,        12/4/2021
74525,  Walmart,     9/10/2021 

I need to get the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

userID, marketplace
74526,  eBay
74525,  eBay

I tried several ways but neither is returning the result without multiple issues or increased complexity, and I am trying to keep the query as little as possible for whoever will maintain it in the future. Is there an easy way to achieve what I am looking for?

>Solution :

You can use the ROW_NUMBER function to get the "first bought" row of each user. Add row numbering with:

row_number() over(partition by userID order by dateOfOrder asc) as r

and then extract where r=1 (first row = first bought based on date ordered ascending):

select userID, marketplace
from (
  select *, row_number() over(partition by userID order by dateOfOrder asc) as r
  from your_table
)
where r=1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading