Query editor
WITH info AS (SELECT blockchain, version, block_time, token_bought_symbol, token_bought_address, token_sold_symbol, token_sold_address, amount_usd, tx_hashFROM dex.tradesWHERE project = 'uniswap'),tokens AS (SELECT date_trunc('month', block_time) AS month, blockchain, token_bought_symbol AS symbol, token_bought_address AS address, amount_usd, tx_hashFROM infoUNION ALLSELECT date_trunc('month', block_time) AS month, blockchain, token_sold_symbol AS symbol, token_sold_address AS address, amount_usd, tx_hashFROM info),TokenStats AS (SELECT blockchain, month, symbol, address, SUM(amount_usd) AS USD_Volume, approx_distinct(tx_hash) AS tx_countFROM tokensGROUP BY blockchain, month, symbol, address),TokenCategory AS (SELECT blockchain, symbol, address, month, tx_count, USD_Volume,CASE WHEN tx_count < 100 AND USD_Volume < 100 THEN 'not active' ELSE 'active' END AS statusFROM TokenStats),ActiveMonths AS (SELECT blockchain, symbol, address, MIN(month) AS create_month, MIN(CASE WHEN status = 'active' THEN month END) AS active_traded_monthFROM TokenCategoryGROUP BY 1,2,3),TokenStatusWithLeads AS (SELECT t.blockchain, t.symbol, t.address, t.month, t.tx_count, t.USD_Volume, t.status,LEAD(t.status, 1) OVER (PARTITION BY t.symbol ORDER BY t.month) AS next_month_status,LEAD(t.status, 2) OVER (PARTITION BY t.symbol ORDER BY t.month) AS next_month_status_2FROM TokenCategory tINNER JOIN ActiveMonths a ON t.symbol = a.symbol AND t.address = a.addressWHERE t.month >= a.active_traded_month),TokenLifeCycle AS (SELECT a.blockchain, a.symbol, a.address, a.create_month, a.active_traded_month,MAX(CASE WHEN ts.status = 'active' THEN ts.month END) AS last_active_traded_month,MAX(ts.month) AS last_trade_monthFROM ActiveMonths aLEFT JOIN TokenStatusWithLeads ts ON a.symbol = ts.symbol AND a.address = ts.addressGROUP BY a.blockchain, a.symbol, a.address, a.create_month, a.active_traded_month)SELECT blockchain, symbol, date_diff('day', create_month, current_date) AS x_days_since_created,CASE WHEN last_active_traded_month NOT IN (date_trunc('month', current_date - interval '3' month), date_trunc('month', current_date - interval '2' month), date_trunc('month', current_date - interval '1' month), date_trunc('month', current_date))THEN CAST(date_diff('month', active_traded_month, last_active_traded_month) AS double) + 1ELSE NULL END AS lifespan,create_month, active_traded_month , last_active_traded_month, last_trade_month, addressFROM TokenLifeCycleWHERE last_trade_month IS NOT NULLORDER BY create_month;