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 compute average Cost in SQL based on category?

So let’s say we have a table called phone.

enter image description here

enter image description here

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

and i need another column to show the average cost of a brand phone
I know i can do something like this:
SELECT brand, AVG (cost)
FROM Phone
GROUP BY brand;

and get something like this table:

enter image description here

Can someone help me how i would get this result below using a select sql statement?

enter image description here

>Solution :

You can use avg(cost) over (partition) such as this:

select *, 
 round(avg(cost) over (partition by brand), 2) as avg_cost
from phone;
phoneid brand cost avg_cost
2 apple 8 10.00
6 apple 12 10.00
3 google 7 6.50
4 google 6 6.50
1 samsung 10 9.33
5 samsung 4 9.33
7 samsung 14 9.33

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