In my rails app I have a typical ecommerce schema inside a Postgres 9.6 database. Here's a simplified version of it:
users table
:name
products table
:name
shopping_carts table
:user_id
line_items table
:price
:qty
:product_id
:shopping_cart_id
I've got a working query to return the number of distinct products bought by each user:
SELECT COUNT(distinct p.*), u.name FROM products p
INNER JOIN line_items l ON p.id = l.product_id
INNER JOIN shopping_carts sc ON l.shopping_cart_id = sc.id
INNER JOIN users u ON sc.user_id = u.id
GROUP BY u.name
But I also want a count of products for each user that only that particular user has purchased. A possible method for this in Ruby (once everything was set up with ActiveRecord) might look something like:
def unique_prod(user)
user.products.select { |p| p.users.length == 1 }.count
end
But how to do it in SQL? I think I need to do it using two counts - one for the number of different user_id
s in a given product's shopping_carts (let's call this count user_count
), and then a count of products for which user_count = 1
. I'm having trouble incorporating the multiple COUNT
and GROUP BY
statements in working fashion. Any suggestions?