Add query based on grouping term