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 can I display top 3 products with its price and arrange by average prices?

I have this records in products table with product_id and its price

product_id price
1 150
1 190
2 20
2 12
3 123
4 513
5 157
5 147

and I want to get the top 3 products and arrange it by average price something like this

product_id price avg_price
4 513 513
1 150 170
1 190 170
5 157 152
5 147 152

how to write/code it in sql query or laravel eloquent query?

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

>Solution :

WITH AverageCTE AS
(
    SELECT product_id, AVG(avg_price) as avg_price 
    FROM products
    GROUP BY product_id
)

SELECT p.product_id, price, avg_price
FROM product p JOIN 
(SELECT * FROM AverageCTE ORDER BY avg_price DESC LIMIT 3) a 
    on p.product_id = a.product_id
ORDER BY avg_price 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