Query editor
WITH events_raw AS (SELECT trace_id, user_position, direction, tx_lt, tx_now, position_size, amm, oracle_price, position_fee,CASE WHEN origin_op = 2774268195 THEN 'increase' ELSE 'decrease_or_close' END AS event_type,2 AS src_rankFROM stormtrade_ton.update_positionUNION ALLSELECT trace_id, user_position, direction, tx_lt, tx_now, position_size, amm, oracle_price, position_fee,CASE WHEN origin_op = 2774268195 THEN 'increase' ELSE 'decrease_or_close' END AS event_type,1 AS src_rankFROM stormtrade_ton.complete_order),events AS (SELECT *FROM (SELECT er.*,ROW_NUMBER() OVER (PARTITION BY er.trace_id, er.ammORDER BY er.src_rank, er.tx_lt, er.trace_id) AS rnFROM events_raw er) xWHERE x.rn = 1),events_with_amounts AS (SELECTe.user_position, e.direction, e.tx_lt, e.tx_now, e.trace_id, e.event_type, e.position_size, e.amm, e.oracle_price, e.position_fee,COALESCE(CAST(tn.locked_amount AS INT256), 0) AS locked_amount,COALESCE(CAST(tn.withdraw_locked_amount AS INT256), 0) AS withdraw_amount,tn.vault_token AS margin_token,tn.trader_addr,tn.origin_addr,COALESCE(CAST(tn.fee_to_stakers AS INT256), 0) AS fee_to_stakers,COALESCE(CAST(tn.free_amount AS INT256), 0) AS free_amount,COALESCE(CAST(tn.exchange_amount AS INT256), 0) AS exchange_amount,COALESCE(CAST(tn.executor_amount AS INT256), 0) AS executor_amountFROM events eLEFT JOIN stormtrade_ton.trade_notification tn ON e.trace_id = tn.trace_id AND e.amm = tn.amm),events_with_sessions AS (SELECTewa.*,SUM(CASE WHEN prev_size = 0 AND position_size <> 0 THEN 1 ELSE 0 END)OVER (PARTITION BY user_position, direction ORDER BY tx_lt, trace_id) AS session_idFROM (SELECT ewa.*, COALESCE(LAG(position_size) OVER (PARTITION BY user_position, direction ORDER BY tx_lt, trace_id), CAST(0 AS INT256)) AS prev_sizeFROM events_with_amounts ewa) ewa),session_last_rows AS (SELECT user_position, direction, session_id, position_size, MAX(tx_now) AS max_tx_nowFROM (SELECT user_position, direction, session_id, position_size, tx_now, ROW_NUMBER() OVER (PARTITION BY user_position, direction, session_id ORDER BY tx_lt DESC, trace_id DESC) AS rn_lastFROM events_with_sessions) sWHERE rn_last = 1GROUP BY user_position, direction, session_id, position_size