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


Block join_result_sample;
                JoinPtr join = expressions.join;
                join_result_sample = JoiningTransform::transformHeader(
                    query_plan.getCurrentDataStream().header, expressions.join);
                QueryPlanStepPtr join_step = std::make_unique<JoinStep>(
                    query_plan.getCurrentDataStream(),
                    expressions.join);
                join_step->setStepDescription("JOIN");
                query_plan.addStep(std::move(join_step));
                if (expressions.join_has_delayed_stream)
                {
                    auto stream = std::make_shared<LazyNonJoinedBlockInputStream>(*join, join_result_sample, settings.max_block_size);
                    auto source = std::make_shared<SourceFromInputStream>(std::move(stream));
                    auto add_non_joined_rows_step = std::make_unique<AddingDelayedSourceStep>(
                            query_plan.getCurrentDataStream(), std::move(source));
                    add_non_joined_rows_step->setStepDescription("Add non-joined rows after JOIN");
                    query_plan.addStep(std::move(add_non_joined_rows_step));
                }
            }
            if (expressions.hasWhere())
                executeWhere(query_plan, expressions.before_where, expressions.remove_where_filter);
            if (expressions.need_aggregate)
            {
                executeAggregation(query_plan, expressions.before_aggregation, aggregate_overflow_row, aggregate_final, query_info.input_order_info);
                
                query_info.input_order_info.reset();
            }
            else
            {
                executeExpression(query_plan, expressions.before_window, "Before window functions");