Donaldino Donaldino - 29 days ago 20
MySQL Question

Trouble referencing two sql tables

For my mySQL database I am trying to display the average of each sectors financial ratios, so I can have a benchmark value per sector.

Companies


| companyName | ticker | sector |

profitability


| ticker | profitMargin | returnOnAssets |

My query so far is this

SELECT c.sector, AVG( p.profitMargin ) , AVG( p.returnOnEquity )
FROM Companies c, profitability p
GROUP BY c.sector


My output shows each sector and their averages, but the values are the same for each tuple, so its not averaging them correctly. Help would be greatly appreciated.

UPDATE*
so i tried the left join and it definitely looks better,

query results

I suppose my problem lies elsewhere due to the NULL values. Because the values are not NULL in the actual relation.

Answer

You need a join

SELECT c.sector, AVG( p.profitMargin ) , AVG( p.returnOnEquity ) 
FROM Companies c
left join  profitability p on c.ticker = p.ticker
GROUP BY c.sector