Query editor
WITH e AS (SELECT token,day,event_class,block_time,tx_hash,token_in,token_outFROM dune.tusa3112.result_rh_top100_provenance_eventsWHERE wallet=0xcb4d28c2106fe9f781615005ff87056d114135c9AND token IS NOT NULL),b AS (SELECT token,MIN(day) day,MIN(block_time) buy_time,SUM(IF(event_class='PAID_BUY',token_in,0e0)) bought_qtyFROM e GROUP BY 1),s0 AS (SELECT e.token,b.day,b.buy_time,b.bought_qty,e.block_time sell_time,e.token_out,ROW_NUMBER() OVER(PARTITION BY e.token ORDER BY e.block_time,e.tx_hash) exit_indexFROM e JOIN b ON b.token=e.tokenWHERE e.event_class='CASH_SELL'),s AS (SELECT *,DATE_DIFF('second',buy_time,sell_time) seconds_after_buy,token_out/NULLIF(bought_qty,0e0) exit_fraction,SUM(token_out) OVER(PARTITION BY token ORDER BY sell_time ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)/NULLIF(bought_qty,0e0) cumulative_exit_fractionFROM s0)SELECT day,exit_index,COUNT(*) tokens,MIN(seconds_after_buy) min_seconds_after_buy,APPROX_PERCENTILE(seconds_after_buy,0.1) p10_seconds_after_buy,APPROX_PERCENTILE(seconds_after_buy,0.5) median_seconds_after_buy,APPROX_PERCENTILE(seconds_after_buy,0.9) p90_seconds_after_buy,MAX(seconds_after_buy) max_seconds_after_buy,APPROX_PERCENTILE(exit_fraction,0.5) median_exit_fraction,MIN(exit_fraction) min_exit_fraction,MAX(exit_fraction) max_exit_fraction,APPROX_PERCENTILE(cumulative_exit_fraction,0.5) median_cumulative_exit_fractionFROM s GROUP BY 1,2 ORDER BY 1,2