Search code examples
sqlt-sqlpivotinner-joinaggregate-functions

Substitute join to leave only one 'Table Scan'


I have financials data. And want to calculate Shareholder's Equity. This is basically how it looks like: enter image description here

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?


Solution

  • 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