Query editor
WITH ReactionAndCommentCounts AS (-- Pre-aggregate reactions and comments from all usersSELECTr.target_hash AS hash,SUM(CASE WHEN r.reaction_type = 1 THEN 1 ELSE 0 END) AS likes_count,SUM(CASE WHEN r.reaction_type = 2 THEN 1 ELSE 0 END) AS recast_count,COUNT(r.reaction_type) AS total_reactions, -- Total reactions (likes + recasts)0 AS comment_count -- Set comment count to 0 for reactionsFROMdune.neynar.dataset_farcaster_reactions rWHEREr.timestamp >= date_add('day', -{{n_days}}, NOW()) -- Subtract n_daysGROUP BY r.target_hashUNION ALL-- Pre-aggregate comments from all usersSELECTc.parent_hash AS hash,0 AS likes_count, -- No likes for comments0 AS recast_count, -- No recasts for comments0 AS total_reactions, -- No reactions for commentsCOUNT(c.hash) AS comment_count -- Count commentsFROMdune.neynar.dataset_farcaster_casts cWHEREc.timestamp >= date_add('day', -{{n_days}}, NOW()) -- Subtract n_daysGROUP BY c.parent_hash),RankedCasts AS (-- Combine reactions and comments, and rank based on total interactionsSELECTe.fid,e.hash,e.timestamp,e.deleted_at AS deleted,DATE_TRUNC('month', e.timestamp) AS month,SUM(COALESCE(rac.total_reactions, 0) + COALESCE(rac.comment_count, 0)) AS total_interactions, -- Combined total of reactions and commentsRANK() OVER (PARTITION BY DATE_TRUNC('month', e.timestamp)ORDER BY SUM(COALESCE(rac.total_reactions, 0) + COALESCE(rac.comment_count, 0)) DESC) AS rankFROMdune.shashankreddy.dataset_farcaster_channels chLEFT JOIN dune.neynar.dataset_farcaster_casts eON e.parent_url = ch.url -- Join casts with channelsLEFT JOIN ReactionAndCommentCounts racON e.hash = rac.hash -- Join pre-aggregated reactions and commentsWHEREch.id = '{{channel_id}}' -- Filter by channel_idAND e.timestamp >= date_add('day', -{{n_days}}, NOW()) -- Subtract n_days-- Apply the thread filter if {{only_threads}} is trueAND (NOT {{only_threads}} OR ({{only_threads}} AND e.root_parent_hash = e.hash))GROUP BY e.fid, e.hash, e.timestamp, e.deleted_at)SELECTr.fid,r.hash,c.text,r.timestamp,