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

How to count the number of unique products purchased by a user?

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).

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

How can the problem be solved?

>Solution :

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

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

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