简体   繁体   中英

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: 在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM