protected function _buildAggregateQuery($query, $config)
    {
        $cases = array();

        $config = AnConfig::unbox($config);
        $config[] = array(
             'WHEN @col(name) LIKE "avatar_edit"  THEN IF(@col(subject.id) = @col(target.id), "", @col(id))',
             'WHEN @col(name) LIKE "actor_follow" THEN @col(subject.id)',
        );

        foreach ($config as $component => $keys) {
            foreach ($keys as $name => $key) {
                if (!is_numeric($name)) {
                    $names = explode(',', $name);
                    $keys = explode(',', $key);

                    foreach ($keys as $i => $key) {
                        $keys[$i] = '@col('.$key.'.id)';
                    }

                    foreach ($names as $name) {
                        $cases[] = 'WHEN CONCAT(@col(name),@col(component)) LIKE \''.$name.$component.'\' THEN CONCAT('.implode(',', $keys).')';
                    }
                } else {
                    $cases[] = $key;
                }
            }
        }

        $cases = array_unique($cases);

        $keys = array();

        //always group by date, name and component
        $date = '@col(name),@col(component),DATE(@col(creationTime))';
        $keys[] = $date;
        if (!empty($cases)) {
            $case = 'CASE TRUE ';
            $case  .= implode(' ', $cases).' ';
            $case  .= 'ELSE CONCAT(@col(target.id),@col(subject.id),@col(object.id)) ';
            $case  .= 'END';
            $keys[] = $case;
        } else {
            $keys[] = '@col(target.id),@col(subject.id),@col(object.id)';
        }

        $keys = implode(',', $keys);
        $comment_if = "IF(@col(comment.id) IS NOT NULL AND @col(object.id) IS NOT NULL , CONCAT_WS(',',$date, @col(object.id)), CONCAT_WS(',',$keys))";
        //don't group if a story has a body or it has directly been commented on
        $bundle = "IF (@col(body) <> '' AND @col(body) IS NOT NULL,@col(id),$comment_if) AS bundle_key";
        $query->select($bundle);
        $query->select('GROUP_CONCAT(DISTINCT @col(id)) AS ids');
        $query->select('GROUP_CONCAT(DISTINCT @col(owner.id))  AS  owner_ids');
        $query->select('GROUP_CONCAT(DISTINCT @col(target.id)) AS   target_ids');
        $query->select('GROUP_CONCAT(DISTINCT @col(comment.id)) AS  comment_ids');
        $query->select('GROUP_CONCAT(DISTINCT @col(object.id)) AS  object_ids');
        $query->select('GROUP_CONCAT(DISTINCT @col(subject.id)) AS subject_ids');
        $query->select(array('id' => 'MAX(@col(id))'));
        $query->select(array('creationTime' => 'MAX(@col(creationTime))'));
        $query->select(array('updateTime' => 'MAX(@col(updateTime))'));
        $viewer = get_viewer();
        $query->group('bundle_key');
        $query->order = array();
        $query->order('modified_on', 'DESC');
    }