Query editor
WITH-- Step 1: Get the latest balance for each delegate up to each proposal creation timelatest_balance AS (SELECTdc.toDelegate,p.proposal_id,vc.newBalance,ROW_NUMBER() OVER (PARTITION BY dc.toDelegate, p.proposal_idORDER BY vc.evt_block_time DESC, vc.evt_index DESC) AS rnFROMgovernance_optimism.proposals pJOIN op_optimism.GovernanceToken_evt_DelegateChanged dcON dc.evt_block_time < p.proposal_created_atJOIN op_optimism.GovernanceToken_evt_DelegateVotesChanged vcON dc.toDelegate = vc.delegateWHEREvc.newBalance > 0),-- Step 2: Filter to get only the latest balance for each delegate up to the proposal creation timefiltered_latest_balance AS (SELECTtoDelegate,proposal_id,newBalanceFROMlatest_balanceWHERErn = 1),-- Step 3: Calculate the total number of distinct delegates per proposaltotal_delegates_per_proposal AS (SELECTproposal_id,COUNT(DISTINCT toDelegate) AS total_delegatesFROMfiltered_latest_balanceGROUP BYproposal_id),-- Step 4: Calculate the number of voted delegates per proposalvoted_delegates AS (SELECTproposal_id,COUNT(DISTINCT voter) AS voted_delegatesFROMgovernance_optimism.proposal_votesGROUP BYproposal_id)-- Step 5: Join the results to get the final outputSELECTp.proposal_id,COALESCE(vd.voted_delegates, 0) AS voted_delegates,COALESCE(td.total_delegates, 0) AS total_delegatesFROMgovernance_optimism.proposals pLEFT JOINvoted_delegates vd ON p.proposal_id = vd.proposal_id