**How to reproduce**
Clickhouse version 21.2-21.3

```
SELECT x
FROM
(
    SELECT 1 AS x
    UNION DISTINCT
    SELECT 1
)
LIMIT 1

Query id: b82bbb8d-dea9-4f1c-9a2f-5b0e9b6c2422


0 rows in set. Elapsed: 0.002 sec.

Received exception from server (version 21.2.3):
Code: 49. DB::Exception: Received from localhost:9000. DB::Exception: Bad cast from type DB::ASTSelectWithUnionQuery to DB::ASTSelectQuery.
```


* If the aggregation is two-level - parallelize to the number of buckets.
      *
      * 2. In one thread, read blocks from different servers in order.
      * RAM stores only one block from each server.
      * If the aggregation is a two-level aggregation, we consistently merge the blocks of each next level.
      *
      * The second option consumes less memory (up to 256 times less)
      *  in the case of two-level aggregation, which is used for large results after GROUP BY,
      *  but it can work more slowly.
      */
    const Settings & settings = context->getSettingsRef();
    Aggregator::Params params(header_before_merge, keys, query_analyzer->aggregates(), overflow_row, settings.max_threads);
    auto transform_params = std::make_shared<AggregatingTransformParams>(params, final);
    auto merging_aggregated = std::make_unique<MergingAggregatedStep>(
            query_plan.getCurrentDataStream(),
            std::move(transform_params),
            settings.distributed_aggregation_memory_efficient,
            settings.max_threads,
            settings.aggregation_memory_efficient_merge_threads);
    query_plan.addStep(std::move(merging_aggregated));
}
void InterpreterSelectQuery::executeHaving(QueryPlan & query_plan, const ActionsDAGPtr & expression)
{
    auto having_step = std::make_unique<FilterStep>(
            query_plan.getCurrentDataStream(),
            expression, getSelectQuery().having()->getColumnName(), false);
    having_step->setStepDescription("HAVING");
    query_plan.addStep(std::move(having_step));
}
void InterpreterSelectQuery::executeTotalsAndHaving(QueryPlan & query_plan, bool has_having, const ActionsDAGPtr & expression, bool overflow_row, bool final)