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

Search for the most popular product in the shop

I have a request:

SELECT * FROM (
    SELECT products.*, count(cheque.product_id) AS countOfOrders FROM products
    JOIN products_to_orders AS cheque ON products.id = cheque.product_id
    GROUP BY products.id
) AS total
WHERE total.countOfOrders > max(countOfOrders);

My task is to find the best selling product in the shop.

In a subquery, I count how many times a product has been ordered.

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

Next, I need to display from this query only the product that was ordered the most.
I am trying to do it with WHERE.
But WHERE disables the use of aggregate functions.
How can I solve my problem?

>Solution :

You can order in the suvquery and take the first.

For mysql

SELECT products.*, count(cheque.product_id) AS countOfOrders FROM products
JOIN products_to_orders AS cheque ON products.id = cheque.product_id
GROUP BY products.id
ORDER by countOfOrders  DESC
LIMIT 1

For sql server

SELECT TOP 1 products.*, count(cheque.product_id) AS countOfOrders FROM products
JOIN products_to_orders AS cheque ON products.id = cheque.product_id
GROUP BY products.id
ORDER by countOfOrders  DESC
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