Given the following example datamodels/tables: (specified in pseudo-Ruby/Rails for brevity's sake)
class User
has_many :orders
end
class Order
has_and_belongs_to_many :products
ordered_at :timestamp
end
class Product
name :string
price :decimal
end
(and each of these tables also has a unique 'id' identifier field that is its primary key, and a joins table connecting Order
and Product
also exists)
I would like to select all users, for which e.g. their oldest Order (with the earliest ordered_at
), contains more than n products.
How can this be done?
What I've tried so far: I tried using a JOIN
, but then we end up looking at all orders rather than only the oldest. I've also tried to use DISTINCT
/DISTINCT ON
but I have no idea how to combine this properly with (a) selecting the users and (b) doing a check for the count of all related products.
I am using Postgres, but if a DB-agnostic SQL answer exists, that would be much appreciated as well.