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

Using SQL calculate average value on each sector

Can you please help me , on how to calculate the average value of the returns on each sector.

**Excepted Output **

Stocks Returns Sector
MS 5.0 IT
Apple 5.0 IT
GEICO 5.0 IT
PETRO 8.5 OIL
BP 8.5 OIL
Citiz 7.0 ENERGY
Utility 7.0 ENERGY

This is what I have tried – But I don’t see the expected result

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

create table table1
(
Stocks varchar(20),
Returns decimal(10,2),
Sector varchar(100)
)

INSERT INTO table1 (Stocks,Returns,Sector) VALUES ('MS','2','IT')
INSERT INTO table1 (Stocks,Returns,Sector) VALUES ('APPL','5','IT')
INSERT INTO table1 (Stocks,Returns,Sector) VALUES ('GEICO','8','IT')
INSERT INTO table1 (Stocks,Returns,Sector) VALUES ('PETRO','10','OIL')
INSERT INTO table1 (Stocks,Returns,Sector) VALUES ('BP','7','OIL')
INSERT INTO table1 (Stocks,Returns,Sector) VALUES ('Citiz','10','ENERGY')
INSERT INTO table1 (Stocks,Returns,Sector) VALUES ('Utility','4','ENERGY')

select Stocks,AVG(Returns) as 'Returns',Sector from table1 group by Stocks,Returns,Sector

>Solution :

You can do it using inner join to join the list of averages by sector

select t.Stocks, s.average, t.Sector
from table1 t
inner join (
  select Sector, AVG(Returns) as 'average'
  from table1 
  group by Sector
) s on s.Sector = t.Sector
order by Sector

Demo here

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