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


&& !filter_info
        && processing_stage == QueryProcessingStage::FetchColumns
        && query_analyzer->hasAggregation()
        && (query_analyzer->aggregates().size() == 1)
        && typeid_cast<AggregateFunctionCount *>(query_analyzer->aggregates()[0].function.get());
    if (optimize_trivial_count)
    {
        const auto & desc = query_analyzer->aggregates()[0];
        const auto & func = desc.function;
        std::optional<UInt64> num_rows{};
        if (!query.prewhere() && !query.where())
            num_rows = storage->totalRows(settings);
        else 
        {
            SelectQueryInfo temp_query_info;
            temp_query_info.query = query_ptr;
            temp_query_info.syntax_analyzer_result = syntax_analyzer_result;
            temp_query_info.sets = query_analyzer->getPreparedSets();
            num_rows = storage->totalRowsByPartitionPredicate(temp_query_info, *context);
        }
        if (num_rows)
        {
            AggregateFunctionCount & agg_count = static_cast<AggregateFunctionCount &>(*func);
            
            std::vector<char> state(agg_count.sizeOfData());
            AggregateDataPtr place = state.data();
            agg_count.create(place);
            SCOPE_EXIT(agg_count.destroy(place));
            agg_count.set(place, *num_rows);
            auto column = ColumnAggregateFunction::create(func);