Home > Software engineering >  How to count the number of unique products purchased by a user?
How to count the number of unique products purchased by a user?

Time:06-20

I have a store database with links like this:

ER-diagram

My task is that I need to display the number of products (unique - those that do not repeat). That is, conditionally, I need to count all the goods purchased by the user, but if I have already counted some goods, do not count it (because it has already been counted).

How can the problem be solved?

CodePudding user response:

SELECT
  o.buyer_id,
  u.first_name || ' ' || u.last_name,
  p.name,
  Sum(po.quantity)
FROM orders o
left JOIN products_to_orders po ON po.order_id = o.id
left JOIN products p ON p.id = po.product_id
left JOIN users u ON u.id = o.buyer_id
GROUP BY o.buyer_id, u.first_name || ' ' || u.last_name, p.name

Group by might be scuffed but I can't really test this

EDIT: added aliases

  • Related