PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 12, 2022

[FIXED] How can I display top 3 products with its price and arrange by average prices?

 February 12, 2022     eloquent, laravel, laravel-8, mysql, sql     No comments   

Issue

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?


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


Answered By - Yuriy Faktorovich
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing