I have financials data. And want to calculate Shareholder's Equity. This is basically how it looks like:
I have the following query which works:
SELECT a.Ticker, a.Value - l.Value as 'ShareholdersEquity'
FROM FinData a
JOIN FinData l
ON a.Ticker = l.Ticker AND a.Date = l.Date
WHERE a.Type = 'assets'
AND l.Type = 'liabilities'
But for a table with many records this will work slowly because when I check the query with Explain (I use Azure Data Studio) and it makes 2 table scans, which means more time. How can I rewrite it to be faster?
You could try conditional aggregation rather than a self-join:
select ticker, date,
sum(case when type = 'asset' then value else - value end) as ShareholdersEquity
from findata
where type in ('asset', 'liabilities')
group by ticker, date