I have a users
table, which has a one-to-many relationship with a user_purchases
table via the foreign key user_id
. That is, each user can make many purchases (or may have none, in which case he will have no entries in the user_purchases table).
user_purchases
has only one other field that is of interest here, which is purchase_date
.
I am trying to write a Sequel ORM statement that will return a dataset with the following columns:
- user_id
- date of the users SECOND purchase, if it exists
So users who have not made at least 2 purchases will not appear in this dataset. What is the best way to write this Sequel statement?
Please note I am looking for a dataset with ALL users returned who have >= 2 purchases
Thanks!
EDIT FOR CLARITY
Here is a similar statement I wrote to get users and their first purchase date (as opposed to 2nd purchase date, which I am asking for help with in the current post):
DB[:users].join(:user_purchases, :user_id => :id)
.select{[:user_id, min(:purchase_date)]}
.group(:user_id)