Query editor
WITHInflowBalances AS (SELECTt.to AS affiliated_address,SUM(t.amount) / 1e18 AS inflowFROM compound_v2_ethereum.Comp_evt_Transfer tWHERE t.to IN (SELECT affiliated_address FROM "query_4340177")GROUP BY t.to),OutflowBalances AS (SELECTt."from" AS affiliated_address,-SUM(t.amount) / 1e18 AS outflowFROM compound_v2_ethereum.Comp_evt_Transfer tWHERE t."from" IN (SELECT affiliated_address FROM "query_4340177")GROUP BY t."from"),DelegatedBalances AS (SELECTd.delegate AS affiliated_address,d.newBalance / 1e18 AS delegated_amount,ROW_NUMBER() OVER (PARTITION BY d.delegateORDER BY d.evt_block_time DESC) AS row_numFROM compound_v2_ethereum.Comp_evt_DelegateVotesChanged dWHERE d.delegate IN (SELECT affiliated_address FROM "query_4340177")),FilteredDelegatedBalances AS (SELECTaffiliated_address,delegated_amountFROM DelegatedBalancesWHERE row_num = 1),FinalWalletBalances AS (SELECTia.affiliated_address,COALESCE(ib.inflow, 0) + COALESCE(ob.outflow, 0) AS current_wallet_balanceFROM "query_4340177" iaLEFT JOIN InflowBalances ib ON ia.affiliated_address = ib.affiliated_addressLEFT JOIN OutflowBalances ob ON ia.affiliated_address = ob.affiliated_address)SELECTfa.affiliated_address,fwb.current_wallet_balance,COALESCE(SUM(fdb.delegated_amount), 0) AS current_delegated_comp,SUM(COALESCE(SUM(fdb.delegated_amount), 0)) OVER () AS total_delegated_compFROM "query_4340177" faLEFT JOIN FinalWalletBalances fwb ON fa.affiliated_address = fwb.affiliated_addressLEFT JOIN FilteredDelegatedBalances fdb ON fa.affiliated_address = fdb.affiliated_addressGROUP BY fa.affiliated_address, fwb.current_wallet_balanceORDER BY fwb.current_wallet_balance DESC, current_delegated_comp DESC