**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.
```


{
    auto expression_before_aggregation = std::make_unique<ExpressionStep>(query_plan.getCurrentDataStream(), expression);
    expression_before_aggregation->setStepDescription("Before GROUP BY");
    query_plan.addStep(std::move(expression_before_aggregation));
    const auto & header_before_aggregation = query_plan.getCurrentDataStream().header;
    ColumnNumbers keys;
    for (const auto & key : query_analyzer->aggregationKeys())
        keys.push_back(header_before_aggregation.getPositionByName(key.name));
    AggregateDescriptions aggregates = query_analyzer->aggregates();
    for (auto & descr : aggregates)
        if (descr.arguments.empty())
            for (const auto & name : descr.argument_names)
                descr.arguments.push_back(header_before_aggregation.getPositionByName(name));
    const Settings & settings = context->getSettingsRef();
    Aggregator::Params params(header_before_aggregation, keys, aggregates,
                              overflow_row, settings.max_rows_to_group_by, settings.group_by_overflow_mode,
                              settings.group_by_two_level_threshold,
                              settings.group_by_two_level_threshold_bytes,
                              settings.max_bytes_before_external_group_by,
                              settings.empty_result_for_aggregation_by_empty_set,
                              context->getTemporaryVolume(),
                              settings.max_threads,
                              settings.min_free_disk_space_for_temporary_data);
    SortDescription group_by_sort_description;