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


{
    OpenTelemetrySpanHolder span(__PRETTY_FUNCTION__);
    query_info.query = query_ptr;
    if (storage && !options.only_analyze)
        from_stage = storage->getQueryProcessingStage(*context, options.to_stage, query_info);
    
    bool first_stage = from_stage < QueryProcessingStage::WithMergeableState
        && options.to_stage >= QueryProcessingStage::WithMergeableState;
    
    bool second_stage = from_stage <= QueryProcessingStage::WithMergeableState
        && options.to_stage > QueryProcessingStage::WithMergeableState;
    analysis_result = ExpressionAnalysisResult(
            *query_analyzer,
            metadata_snapshot,
            first_stage,
            second_stage,
            options.only_analyze,
            filter_info,
            source_header);
    if (options.to_stage == QueryProcessingStage::Enum::FetchColumns)
    {
        auto header = source_header;
        if (analysis_result.prewhere_info)
        {
            ExpressionActions(analysis_result.prewhere_info->prewhere_actions).execute(header);
            if (analysis_result.prewhere_info->remove_prewhere_column)
                header.erase(analysis_result.prewhere_info->prewhere_column_name);
        }
        return header;
    }