Query editor
WITH target_token AS (-- Use a CTE for the token address to make it easy to swapSELECT 0x302DFaF2CDbE51a18d97186A7384e87CF599877D AS token_addr),trades AS (SELECTt.block_time,t.tx_from AS wallet,t.tx_hash,t.token_bought_amount,t.token_sold_amount,t.amount_usd,CASEWHEN t.token_bought_address = tt.token_addr THEN 'buy'WHEN t.token_sold_address = tt.token_addr THEN 'sell'END AS sideFROM dex.trades tCROSS JOIN target_token ttWHERE (t.token_bought_address = tt.token_addr OR t.token_sold_address = tt.token_addr)AND t.blockchain = 'bnb'AND t.block_time >= TIMESTAMP '2026-02-23'AND t.block_time < TIMESTAMP '2026-03-10'),wallet_summary AS (SELECTwallet,SUM(CASE WHEN side = 'buy' THEN token_bought_amount ELSE 0 END) AS total_bought,SUM(CASE WHEN side = 'sell' THEN token_sold_amount ELSE 0 END) AS total_sold,SUM(CASE WHEN side = 'buy' THEN amount_usd ELSE 0 END) AS total_usd_spent,SUM(CASE WHEN side = 'sell' THEN amount_usd ELSE 0 END) AS total_usd_earned,MIN(block_time) AS first_buy_timeFROM tradesGROUP BY wallet),first_tx AS (-- Get the hash of the very first buy using ROW_NUMBER instead of DISTINCT ONSELECTwallet,tx_hashFROM (SELECTwallet,tx_hash,ROW_NUMBER() OVER (PARTITION BY wallet ORDER BY block_time ASC) AS rnFROM tradesWHERE side = 'buy') rankedWHERE rn = 1)SELECTws.wallet,ws.first_buy_time,ft.tx_hash AS first_buy_tx_hash,ws.total_bought,ws.total_sold,(ws.total_bought - ws.total_sold) AS tokens_held,ws.total_usd_spent,ws.total_usd_earned,(ws.total_usd_earned - ws.total_usd_spent) AS realized_pnl_usd,ROUND(100 * (ws.total_usd_earned - ws.total_usd_spent) / NULLIF(ws.total_usd_spent, 0), 2) AS roi_pct